org.elasticsearch.common.xcontent.XContentBuilder Java Examples

The following examples show how to use org.elasticsearch.common.xcontent.XContentBuilder. 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: ESConnector.java    From Siamese with 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 #2
Source File: SearchIntoResponse.java    From elasticsearch-inout-plugin with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: KafkaConsumerTest.java    From SkyEye with 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 #4
Source File: ProfileResult.java    From Elasticsearch with 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 #5
Source File: RangeQueryBuilder.java    From Elasticsearch with 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 #6
Source File: StoredFeature.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: InternalStats.java    From Elasticsearch with 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 #8
Source File: PointCollection.java    From Elasticsearch with 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 #9
Source File: SpanOrQueryBuilder.java    From Elasticsearch with 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 #10
Source File: RestDeleteIndexedScriptAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: CoordinateSearchMetadata.java    From siren-join with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #12
Source File: MergeStats.java    From Elasticsearch with 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 #13
Source File: TermVectorsResponse.java    From Elasticsearch with 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 #14
Source File: MultiValuesSourceAggregationBuilder.java    From elasticsearch-linear-regression with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: ElasticSearchServiceMapper.java    From vertx-elasticsearch-service with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: InternalCardinality.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
    final long cardinality = getValue();
    builder.field(CommonFields.VALUE, cardinality);
    if (!(valueFormatter instanceof ValueFormatter.Raw)) {
        builder.field(CommonFields.VALUE_AS_STRING, valueFormatter.format(cardinality));
    }
    return builder;
}
 
Example #17
Source File: ClearFilterJoinCacheResponse.java    From siren-join with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
  builder.field("cluster_name", getClusterName().value());

  builder.startObject("nodes");
  for (ClearFilterJoinCacheNodeResponse node : this) {
    builder.startObject(node.getNode().getName(), XContentBuilder.FieldCaseConversion.NONE);
    builder.field("timestamp", node.getTimestamp());
    builder.endObject();
  }
  builder.endObject();

  return builder;
}
 
Example #18
Source File: SuggestRequestBuilder.java    From elasticshell with Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder toXContent(SuggestRequest request, SuggestResponse response, XContentBuilder builder) throws IOException {
    builder.startObject();
    buildBroadcastShardsHeader(builder, response);
    Suggest suggest = response.getSuggest();
    if (suggest != null) {
        suggest.toXContent(builder, ToXContent.EMPTY_PARAMS);
    }
    builder.endObject();
    return builder;
}
 
Example #19
Source File: MinHashFieldMapper.java    From elasticsearch-minhash with Apache License 2.0 5 votes vote down vote up
public XContentBuilder toXContent(final XContentBuilder builder,
        final Params params) throws IOException {
    if (!copyBitsToFields.isEmpty()) {
        builder.startArray("copy_bits_to");
        for (final String field : copyBitsToFields) {
            builder.value(field);
        }
        builder.endArray();
    }
    return builder;
}
 
Example #20
Source File: IndexShardStatsResponse.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    try {
        XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
        builder.startObject();
        toXContent(builder, EMPTY_PARAMS);
        builder.endObject();
        return builder.string();
    } catch (IOException e) {
        return "{ \"error\" : \"" + e.getMessage() + "\"}";
    }
}
 
Example #21
Source File: SiteElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
protected XContentBuilder addFields(XContentBuilder contentSourceBuilder, String resourceName,
                                    EntityContentProducer ecp, boolean includeContent) throws IOException {
    return contentSourceBuilder.field(SearchService.FIELD_SITEID, ecp.getSiteId(resourceName))
            .field(SearchService.FIELD_TITLE, ecp.getTitle(resourceName))
            .field(SearchService.FIELD_REFERENCE, resourceName)
            .field(SearchService.FIELD_URL, ecp.getUrl(resourceName, Entity.UrlType.PORTAL))
            //.field(SearchService.FIELD_ID, ecp.getId(resourceName))
            .field(SearchService.FIELD_TOOL, ecp.getTool())
            .field(SearchService.FIELD_CONTAINER, ecp.getContainer(resourceName))
            .field(SearchService.FIELD_TYPE, ecp.getType(resourceName));
            //.field(SearchService.FIELD_SUBTYPE, ecp.getSubType(resourceName));
}
 
Example #22
Source File: UserDefinedFunctionsMetaData.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startArray("functions");
    for (UserDefinedFunctionMetaData function : functionsMetaData) {
        function.toXContent(builder, params);
    }
    builder.endArray();
    return builder;
}
 
Example #23
Source File: Elasticsearch2Client.java    From presto-connectors with Apache License 2.0 5 votes vote down vote up
@Override
public void createTable(ConnectorTableMetadata tableMetadata)
{
    XContentBuilder mapping = getMapping(tableMetadata.getColumns());
    String index = tableMetadata.getTable().getTableName();
    try {
        //TODO: default type value is presto
        client.admin().indices().prepareCreate(index)
                .addMapping("presto", mapping)
                .execute().actionGet();
    }
    catch (MapperParsingException e) {
        throw new PrestoException(ES_MAPPING_ERROR, "Failed create index:" + index, e);
    }
}
 
Example #24
Source File: IndicesExistsRequestBuilder.java    From elasticshell with Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder toXContent(IndicesExistsRequest request, IndicesExistsResponse response, XContentBuilder builder) throws IOException {
    builder.startObject();
    builder.field(Fields.OK, response.isExists());
    builder.endObject();
    return builder;
}
 
Example #25
Source File: Text.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    if (hasString()) {
        return builder.value(this.string());
    } else {
        // TODO: TextBytesOptimization we can use a buffer here to convert it? maybe add a
        // request to jackson to support InputStream as well?
        BytesRef br = this.bytes().toBytesRef();
        return builder.utf8Value(br.bytes, br.offset, br.length);
    }
}
 
Example #26
Source File: Template.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder scriptFieldToXContent(String template, ScriptType type, XContentBuilder builder, Params builderParams)
        throws IOException {
    if (type == ScriptType.INLINE && contentType != null && builder.contentType() == contentType) {
        builder.rawField(type.getParseField().getPreferredName(), new BytesArray(template));
    } else {
        builder.field(type.getParseField().getPreferredName(), template);
    }
    return builder;
}
 
Example #27
Source File: PutMappingRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    if (source != null) {
        try (InputStream stream = new BytesArray(source).streamInput()) {
            builder.rawValue(stream, XContentType.JSON);
        }
    } else {
        builder.startObject().endObject();
    }
    return builder;
}
 
Example #28
Source File: RestExecuteAnomalyDetectorAction.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private RestActionListener<GetResponse> onGetAnomalyDetectorResponse(RestChannel channel, AnomalyDetectorExecutionInput input) {
    return new RestActionListener<GetResponse>(channel) {
        @Override
        protected void processResponse(GetResponse response) throws Exception {
            if (!response.isExists()) {
                XContentBuilder message = channel
                    .newErrorBuilder()
                    .startObject()
                    .field("message", "Can't find anomaly detector with id:" + response.getId())
                    .endObject();
                channel.sendResponse(new BytesRestResponse(RestStatus.NOT_FOUND, message));
                return;
            }
            XContentParser parser = XContentType.JSON
                .xContent()
                .createParser(
                    channel.request().getXContentRegistry(),
                    LoggingDeprecationHandler.INSTANCE,
                    response.getSourceAsBytesRef().streamInput()
                );

            ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
            AnomalyDetector detector = AnomalyDetector.parse(parser, response.getId(), response.getVersion());

            anomalyDetectorRunner
                .executeDetector(
                    detector,
                    input.getPeriodStart(),
                    input.getPeriodEnd(),
                    getPreviewDetectorActionListener(channel, detector)
                );
        }
    };
}
 
Example #29
Source File: GeometryCollectionBuilder.java    From Elasticsearch with 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.startArray(FIELD_GEOMETRIES);
    for (ShapeBuilder shape : shapes) {
        shape.toXContent(builder, params);
    }
    builder.endArray();
    return builder.endObject();
}
 
Example #30
Source File: PhraseSuggestionBuilder.java    From Elasticsearch with 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;
}