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

The following examples show how to use org.elasticsearch.common.xcontent.XContentBuilder#startArray() . 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: MultiGetResponse.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.startArray(Fields.DOCS);
    for (MultiGetItemResponse response : responses) {
        if (response.isFailed()) {
            builder.startObject();
            Failure failure = response.getFailure();
            builder.field(Fields._INDEX, failure.getIndex());
            builder.field(Fields._TYPE, failure.getType());
            builder.field(Fields._ID, failure.getId());
            ElasticsearchException.renderThrowable(builder, params, failure.getFailure());
            builder.endObject();
        } else {
            GetResponse getResponse = response.getResponse();
            builder.startObject();
            getResponse.toXContent(builder, params);
            builder.endObject();
        }
    }
    builder.endArray();
    return builder;
}
 
Example 2
Source File: PendingClusterTasksResponse.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.startArray(Fields.TASKS);
    for (PendingClusterTask pendingClusterTask : this) {
        builder.startObject();
        builder.field(Fields.INSERT_ORDER, pendingClusterTask.getInsertOrder());
        builder.field(Fields.PRIORITY, pendingClusterTask.getPriority());
        builder.field(Fields.SOURCE, pendingClusterTask.getSource());
        builder.field(Fields.EXECUTING, pendingClusterTask.isExecuting());
        builder.field(Fields.TIME_IN_QUEUE_MILLIS, pendingClusterTask.getTimeInQueueInMillis());
        builder.field(Fields.TIME_IN_QUEUE, pendingClusterTask.getTimeInQueue());
        builder.endObject();
    }
    builder.endArray();
    return builder;
}
 
Example 3
Source File: RestTable.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static RestResponse buildXContentBuilder(Table table, RestChannel channel) throws Exception {
    RestRequest request = channel.request();
    XContentBuilder builder = channel.newBuilder();
    List<DisplayHeader> displayHeaders = buildDisplayHeaders(table, request);

    builder.startArray();
    for (int row = 0; row < table.getRows().size(); row++) {
        builder.startObject();
        for (DisplayHeader header : displayHeaders) {
            builder.field(header.display, renderValue(request, table.getAsMap().get(header.name).get(row).value));
        }
        builder.endObject();

    }
    builder.endArray();
    return new BytesRestResponse(RestStatus.OK, builder);
}
 
Example 4
Source File: AnalyzeResponse.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    if (tokens != null) {
        builder.startArray(Fields.TOKENS);
        for (AnalyzeToken token : tokens) {
            token.toXContent(builder, params);
        }
        builder.endArray();
    }

    if (detail != null) {
        builder.startObject(Fields.DETAIL);
        detail.toXContent(builder, params);
        builder.endObject();
    }
    return builder;
}
 
Example 5
Source File: DisMaxQueryBuilder.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(DisMaxQueryParser.NAME);
    if (tieBreaker != -1) {
        builder.field("tie_breaker", tieBreaker);
    }
    if (boost != -1) {
        builder.field("boost", boost);
    }
    if (queryName != null) {
        builder.field("_name", queryName);
    }
    builder.startArray("queries");
    for (QueryBuilder queryBuilder : queries) {
        queryBuilder.toXContent(builder, params);
    }
    builder.endArray();
    builder.endObject();
}
 
Example 6
Source File: SnapshotDeletionsInProgress.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startArray(TYPE);
    for (Entry entry : entries) {
        builder.startObject();
        {
            builder.field("repository", entry.snapshot.getRepository());
            builder.field("snapshot", entry.snapshot.getSnapshotId().getName());
            builder.humanReadableField("start_time_millis", "start_time", new TimeValue(entry.startTime));
            builder.field("repository_state_id", entry.repositoryStateId);
        }
        builder.endObject();
    }
    builder.endArray();
    return builder;
}
 
Example 7
Source File: ShapeBuilder.java    From crate 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 coord : coordinates) {
        toXContent(builder, coord);
    }
    if (closed) {
        Coordinate start = coordinates.get(0);
        Coordinate end = coordinates.get(coordinates.size() - 1);
        if (start.x != end.x || start.y != end.y) {
            toXContent(builder, coordinates.get(0));
        }
    }
    builder.endArray();
    return builder;
}
 
Example 8
Source File: Search.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
public static void buildTimeline(XContentBuilder builder,
		SearchResponse response, ESLogger logger) throws IOException {
	logger.info("Report took in millseconds:" + response.getTookInMillis());
	DateHistogram timeline = response.getAggregations().get(
			"data_over_time");

	// 格式化结果后输出

	builder.startObject();
	builder.field("took", response.getTookInMillis());
	builder.field("total", timeline.getBuckets().size());

	builder.startArray("fields");
	builder.value("_bucket_timevalue");
	builder.value("_doc_count");
	builder.endArray();

	builder.startArray("rows");
	for (Bucket bucket : timeline.getBuckets()) {
		builder.startArray();
		builder.value(bucket.getKey());
		builder.value(bucket.getDocCount());
		builder.endArray();
	}
	builder.endArray().endObject();

}
 
Example 9
Source File: StringTerms.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
    builder.field(InternalTerms.DOC_COUNT_ERROR_UPPER_BOUND_FIELD_NAME, docCountError);
    builder.field(SUM_OF_OTHER_DOC_COUNTS, otherDocCount);
    builder.startArray(CommonFields.BUCKETS);
    for (InternalTerms.Bucket bucket : buckets) {
        bucket.toXContent(builder, params);
    }
    builder.endArray();
    return builder;
}
 
Example 10
Source File: BasePolygonBuilder.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_COORDINATES);
    coordinatesArray(builder, params);
    builder.endArray();
    builder.endObject();
    return builder;
}
 
Example 11
Source File: ExplainRequestBuilder.java    From elasticshell with Apache License 2.0 5 votes vote down vote up
private void buildExplanation(XContentBuilder builder, Explanation explanation) throws IOException {
    builder.field(Fields.VALUE, explanation.getValue());
    builder.field(Fields.DESCRIPTION, explanation.getDescription());
    Explanation[] innerExps = explanation.getDetails();
    if (innerExps != null) {
        builder.startArray(Fields.DETAILS);
        for (Explanation exp : innerExps) {
            builder.startObject();
            buildExplanation(builder, exp);
            builder.endObject();
        }
        builder.endArray();
    }
}
 
Example 12
Source File: GeoDistanceBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder internalXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject();
    if (ranges.isEmpty()) {
        throw new SearchSourceBuilderException("at least one range must be defined for geo_distance aggregation [" + getName() + "]");
    }
    if (point == null) {
        throw new SearchSourceBuilderException("center point must be defined for geo_distance aggregation [" + getName() + "]");
    }

    if (field != null) {
        builder.field("field", field);
    }

    if (unit != null) {
        builder.field("unit", unit);
    }

    if (distanceType != null) {
        builder.field("distance_type", distanceType.name().toLowerCase(Locale.ROOT));
    }

    builder.startObject("center")
            .field("lat", point.lat())
            .field("lon", point.lon())
            .endObject();

    builder.startArray("ranges");
    for (Range range : ranges) {
        range.toXContent(builder, params);
    }
    builder.endArray();

    return builder.endObject();
}
 
Example 13
Source File: ClusterIndexHealth.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.field(Fields.STATUS, getStatus().name().toLowerCase(Locale.ROOT));
    builder.field(Fields.NUMBER_OF_SHARDS, getNumberOfShards());
    builder.field(Fields.NUMBER_OF_REPLICAS, getNumberOfReplicas());
    builder.field(Fields.ACTIVE_PRIMARY_SHARDS, getActivePrimaryShards());
    builder.field(Fields.ACTIVE_SHARDS, getActiveShards());
    builder.field(Fields.RELOCATING_SHARDS, getRelocatingShards());
    builder.field(Fields.INITIALIZING_SHARDS, getInitializingShards());
    builder.field(Fields.UNASSIGNED_SHARDS, getUnassignedShards());

    if (!getValidationFailures().isEmpty()) {
        builder.startArray(Fields.VALIDATION_FAILURES);
        for (String validationFailure : getValidationFailures()) {
            builder.value(validationFailure);
        }
        builder.endArray();
    }

    if ("shards".equals(params.param("level", "indices"))) {
        builder.startObject(Fields.SHARDS);

        for (ClusterShardHealth shardHealth : shards.values()) {
            builder.startObject(Integer.toString(shardHealth.getId()));

            builder.field(Fields.STATUS, shardHealth.getStatus().name().toLowerCase(Locale.ROOT));
            builder.field(Fields.PRIMARY_ACTIVE, shardHealth.isPrimaryActive());
            builder.field(Fields.ACTIVE_SHARDS, shardHealth.getActiveShards());
            builder.field(Fields.RELOCATING_SHARDS, shardHealth.getRelocatingShards());
            builder.field(Fields.INITIALIZING_SHARDS, shardHealth.getInitializingShards());
            builder.field(Fields.UNASSIGNED_SHARDS, shardHealth.getUnassignedShards());

            builder.endObject();
        }

        builder.endObject();
    }
    return builder;
}
 
Example 14
Source File: ElasticsearchException.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void xContentHeader(XContentBuilder builder, String key, List<String> values) throws IOException {
    if (values != null && values.isEmpty() == false) {
        if(values.size() == 1) {
            builder.field(key, values.get(0));
        } else {
            builder.startArray(key);
            for (String value : values) {
                builder.value(value);
            }
            builder.endArray();
        }
    }
}
 
Example 15
Source File: MultiPolygonBuilder.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.startObject();
    builder.field(ShapeParser.FIELD_TYPE.getPreferredName(), TYPE.shapeName());
    builder.field(ShapeParser.FIELD_ORIENTATION.getPreferredName(), orientation.name().toLowerCase(Locale.ROOT));
    builder.startArray(ShapeParser.FIELD_COORDINATES.getPreferredName());
    for (PolygonBuilder polygon : polygons) {
        builder.startArray();
        polygon.coordinatesArray(builder, params);
        builder.endArray();
    }
    builder.endArray();
    return builder.endObject();
}
 
Example 16
Source File: CoordinateSearchMetadata.java    From siren-join with GNU Affero General Public License v3.0 5 votes vote down vote up
public XContentBuilder toXContent(XContentBuilder builder) throws IOException {
  builder.startObject(Fields.COORDINATE_SEARCH);

  builder.startArray(Fields.ACTIONS);
  for (Action action : this.actions) {
    action.toXContent(builder);
  }
  builder.endArray();

  builder.endObject();
  return builder;
}
 
Example 17
Source File: MultiLineStringBuilder.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.field(FIELD_COORDINATES);
    builder.startArray();
    for(BaseLineStringBuilder<?> line : lines) {
        line.coordinatesToXcontent(builder, false);
    }
    builder.endArray();
    builder.endObject();
    return builder;
}
 
Example 18
Source File: VertexiumQueryStringQueryBuilder.java    From vertexium with Apache License 2.0 5 votes vote down vote up
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject("vertexium_query_string");
    super.doXContent(builder, params);

    builder.startArray("authorizations");
    for (String authorization : authorizations) {
        builder.value(authorization);
    }
    builder.endArray();

    builder.endObject();
}
 
Example 19
Source File: UpgradeStatusResponse.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.byteSizeField(Fields.SIZE_IN_BYTES, Fields.SIZE, getTotalBytes());
    builder.byteSizeField(Fields.SIZE_TO_UPGRADE_IN_BYTES, Fields.SIZE_TO_UPGRADE, getToUpgradeBytes());
    builder.byteSizeField(Fields.SIZE_TO_UPGRADE_ANCIENT_IN_BYTES, Fields.SIZE_TO_UPGRADE_ANCIENT, getToUpgradeBytesAncient());

    String level = params.param("level", "indices");
    boolean outputShards = "shards".equals(level);
    boolean outputIndices = "indices".equals(level) || outputShards;
    if (outputIndices) {
        builder.startObject(Fields.INDICES);
        for (IndexUpgradeStatus indexUpgradeStatus : getIndices().values()) {
            builder.startObject(indexUpgradeStatus.getIndex(), XContentBuilder.FieldCaseConversion.NONE);

            builder.byteSizeField(Fields.SIZE_IN_BYTES, Fields.SIZE, indexUpgradeStatus.getTotalBytes());
            builder.byteSizeField(Fields.SIZE_TO_UPGRADE_IN_BYTES, Fields.SIZE_TO_UPGRADE, indexUpgradeStatus.getToUpgradeBytes());
            builder.byteSizeField(Fields.SIZE_TO_UPGRADE_ANCIENT_IN_BYTES, Fields.SIZE_TO_UPGRADE_ANCIENT, indexUpgradeStatus.getToUpgradeBytesAncient());
            if (outputShards) {
                builder.startObject(Fields.SHARDS);
                for (IndexShardUpgradeStatus indexShardUpgradeStatus : indexUpgradeStatus) {
                    builder.startArray(Integer.toString(indexShardUpgradeStatus.getShardId().id()));
                    for (ShardUpgradeStatus shardUpgradeStatus : indexShardUpgradeStatus) {
                        builder.startObject();

                        builder.byteSizeField(Fields.SIZE_IN_BYTES, Fields.SIZE, getTotalBytes());
                        builder.byteSizeField(Fields.SIZE_TO_UPGRADE_IN_BYTES, Fields.SIZE_TO_UPGRADE, getToUpgradeBytes());
                        builder.byteSizeField(Fields.SIZE_TO_UPGRADE_ANCIENT_IN_BYTES, Fields.SIZE_TO_UPGRADE_ANCIENT, getToUpgradeBytesAncient());

                        builder.startObject(Fields.ROUTING);
                        builder.field(Fields.STATE, shardUpgradeStatus.getShardRouting().state());
                        builder.field(Fields.PRIMARY, shardUpgradeStatus.getShardRouting().primary());
                        builder.field(Fields.NODE, shardUpgradeStatus.getShardRouting().currentNodeId());
                        if (shardUpgradeStatus.getShardRouting().relocatingNodeId() != null) {
                            builder.field(Fields.RELOCATING_NODE, shardUpgradeStatus.getShardRouting().relocatingNodeId());
                        }
                        builder.endObject();

                        builder.endObject();
                    }
                    builder.endArray();
                }
                builder.endObject();
            }
            builder.endObject();
        }
        builder.endObject();
    }
    return builder;
}
 
Example 20
Source File: NeuronIndexer.java    From bluima with Apache License 2.0 4 votes vote down vote up
/** Indexes neuron and properties at the sentence level. */
@Override
protected List<IndexRequestBuilder> toRequest(JCas jCas, Client client,
		String indexName) throws IOException {
	List<IndexRequestBuilder> requests = newArrayList();

	String pmId = getHeaderDocId(jCas);

	try {
		// UIMA CAS indexes so that we build them once for all sentences.
		Map<AnnotationFS, Collection<AnnotationFS>> idxNeuron = indexCovered(
				jCas.getCas(), //
				getType(jCas, Sentence.class), getType(jCas, Neuron.class));
		Map<AnnotationFS, Collection<AnnotationFS>> idxNeuronProperties = indexCovered(
				jCas.getCas(), //
				getType(jCas, Neuron.class),
				getType(jCas, NeuronProperty.class));
		Map<AnnotationFS, Collection<AnnotationFS>> idxNeurons = indexCovered(
				jCas.getCas(), //
				getType(jCas, Neuron.class),
				getType(jCas, NeuronTrigger.class));

		for (Sentence s : select(jCas, Sentence.class)) {

			// only index sentences that contain a neuron
			if (!(onlyIndexNeurons && idxNeuron.get(s).isEmpty())) {

				int sentenceStart = s.getBegin();

				final XContentBuilder doc = jsonBuilder().startObject();
				doc.field(FIELD_PUBMED_ID, pmId);
				doc.field(FIELD_SENTENCE_TEXT, s.getCoveredText());
				doc.field(FIELD_SENTENCE_ID, sentenceStart);

				doc.startArray("neuron");

				for (AnnotationFS nwp_ : idxNeuron.get(s)) {
					Neuron nwp = (Neuron) nwp_;
					doc.startObject();
					doc.field(FIELD_NEURON_TEXT, nwp.getCoveredText());
					doc.field(FIELD_START, nwp.getBegin() - sentenceStart);
					doc.field(FIELD_END, nwp.getEnd() - sentenceStart);

					// properties
					doc.startArray("neuron_properties");
					// neuron(trigger), handle as it were a property
					NeuronTrigger n = ((NeuronTrigger) (idxNeurons.get(nwp)
							.iterator().next()));
					doc.startObject();
					doc.field(FIELD_NEURON_TYPE, n.getType().getShortName()
							.replaceAll("Prop$", ""));
					doc.field(FIELD_PROPERTY_TEXT, n.getCoveredText());
					doc.field(FIELD_START, n.getBegin() - sentenceStart);
					doc.field(FIELD_END, n.getEnd() - sentenceStart);
					doc.endObject(); // end 'n' (neuron trigger)

					// every NeuronProperty
					if (idxNeuronProperties.containsKey(nwp)) {
						for (AnnotationFS np : idxNeuronProperties.get(nwp)) {
							doc.startObject();
							doc.field(FIELD_NEURON_TYPE, np.getType()
									.getShortName().replaceAll("Prop$", ""));
							doc.field(FIELD_PROPERTY_TEXT,
									np.getCoveredText());
							doc.field(FIELD_START, np.getBegin()
									- sentenceStart);
							doc.field(FIELD_END, np.getEnd()
									- sentenceStart);
							doc.endObject();
						}
					}
					doc.endArray(); // end 'properties'
					doc.endObject(); // end nwp
				}
				doc.endArray(); // end 'neuron'

				String uid = pmId + "_" + sentenceStart; // uid for Lucene
				requests.add(client
						.prepareIndex(indexName, "sentence", uid)
						.setSource(doc));

				LOG.trace(doc.string());
			}
		}
	} catch (Exception e) {
		LOG.warn("could not index pmid" + pmId, e);
	}
	return requests;
}