当前位置: 首页>>代码示例>>Java>>正文


Java XContentHelper类代码示例

本文整理汇总了Java中org.elasticsearch.common.xcontent.XContentHelper的典型用法代码示例。如果您正苦于以下问题:Java XContentHelper类的具体用法?Java XContentHelper怎么用?Java XContentHelper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


XContentHelper类属于org.elasticsearch.common.xcontent包,在下文中一共展示了XContentHelper类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: execute

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
@Override
public void execute(IngestDocument document) throws Exception {
    String stringValue = document.getFieldValue(field, String.class);
    try {
        Map<String, Object> mapValue = XContentHelper.convertToMap(JsonXContent.jsonXContent, stringValue, false);
        if (addToRoot) {
            for (Map.Entry<String, Object> entry : mapValue.entrySet()) {
                document.setFieldValue(entry.getKey(), entry.getValue());
            }
        } else {
            document.setFieldValue(targetField, mapValue);
        }
    } catch (ElasticsearchParseException e) {
        throw new IllegalArgumentException(e);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:JsonProcessor.java

示例2: testEmbeddedToJSON

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
public void testEmbeddedToJSON() throws Exception {
    XContentBuilder builder = jsonBuilder().startObject()
                    .startArray("bulks")
                        .startObject()
                            .field("index", "index-1")
                            .field("type", "type-1")
                            .field("id", 1)
                        .endObject()
                        .startObject()
                            .field("index", "index-2")
                            .field("type", "type-2")
                            .field("id", 2)
                        .endObject()
                    .endArray()
                .endObject();

    Map<String, Object> ctx =
        Collections.singletonMap("ctx", XContentHelper.convertToMap(builder.bytes(), false, builder.contentType()).v2());

    assertScript("{{#ctx.bulks}}{{#toJson}}.{{/toJson}}{{/ctx.bulks}}", ctx,
            equalTo("{\"index\":\"index-1\",\"id\":1,\"type\":\"type-1\"}{\"index\":\"index-2\",\"id\":2,\"type\":\"type-2\"}"));

    assertScript("{{#ctx.bulks}}<{{#toJson}}id{{/toJson}}>{{/ctx.bulks}}", ctx,
            equalTo("<1><2>"));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:26,代码来源:MustacheTests.java

示例3: validatePipeline

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
void validatePipeline(Map<DiscoveryNode, IngestInfo> ingestInfos, PutPipelineRequest request) throws Exception {
    if (ingestInfos.isEmpty()) {
        throw new IllegalStateException("Ingest info is empty");
    }

    Map<String, Object> pipelineConfig = XContentHelper.convertToMap(request.getSource(), false, request.getXContentType()).v2();
    Pipeline pipeline = factory.create(request.getId(), pipelineConfig, processorFactories);
    List<Exception> exceptions = new ArrayList<>();
    for (Processor processor : pipeline.flattenAllProcessors()) {
        for (Map.Entry<DiscoveryNode, IngestInfo> entry : ingestInfos.entrySet()) {
            if (entry.getValue().containsProcessor(processor.getType()) == false) {
                String message = "Processor type [" + processor.getType() + "] is not installed on node [" + entry.getKey() + "]";
                exceptions.add(ConfigurationUtils.newConfigurationException(processor.getType(), processor.getTag(), null, message));
            }
        }
    }
    ExceptionsHelper.rethrowAndSuppress(exceptions);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:PipelineStore.java

示例4: parseDocument

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
ParsedDocument parseDocument(SourceToParse source) throws MapperParsingException {
    validateType(source);

    final Mapping mapping = docMapper.mapping();
    final ParseContext.InternalParseContext context;
    try (XContentParser parser = XContentHelper.createParser(docMapperParser.getXContentRegistry(), source.source())) {
        context = new ParseContext.InternalParseContext(indexSettings.getSettings(),
                docMapperParser, docMapper, source, parser);
        validateStart(parser);
        internalParseDocument(mapping, context, parser);
        validateEnd(parser);
    } catch (Exception e) {
        throw wrapInMapperParsingException(source, e);
    }
    String remainingPath = context.path().pathAsText("");
    if (remainingPath.isEmpty() == false) {
        throw new IllegalStateException("found leftover path elements: " + remainingPath);
    }

    reverseOrder(context);

    ParsedDocument doc = parsedDocument(source, context, createDynamicUpdate(mapping, docMapper, context.getDynamicMappers()));
    return doc;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:DocumentParser.java

示例5: toXContent

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
public static void toXContent(AliasMetaData aliasMetaData, XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject(aliasMetaData.alias());

    boolean binary = params.paramAsBoolean("binary", false);

    if (aliasMetaData.filter() != null) {
        if (binary) {
            builder.field("filter", aliasMetaData.filter.compressed());
        } else {
            builder.field("filter", XContentHelper.convertToMap(new BytesArray(aliasMetaData.filter().uncompressed()), true).v2());
        }
    }
    if (aliasMetaData.indexRouting() != null) {
        builder.field("index_routing", aliasMetaData.indexRouting());
    }
    if (aliasMetaData.searchRouting() != null) {
        builder.field("search_routing", aliasMetaData.searchRouting());
    }

    builder.endObject();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:22,代码来源:AliasMetaData.java

示例6: doExecute

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
@Override
protected void doExecute(SimulatePipelineRequest request, ActionListener<SimulatePipelineResponse> listener) {
    final Map<String, Object> source = XContentHelper.convertToMap(request.getSource(), false, request.getXContentType()).v2();

    final SimulatePipelineRequest.Parsed simulateRequest;
    try {
        if (request.getId() != null) {
            simulateRequest = SimulatePipelineRequest.parseWithPipelineId(request.getId(), source, request.isVerbose(), pipelineStore);
        } else {
            simulateRequest = SimulatePipelineRequest.parse(source, request.isVerbose(), pipelineStore);
        }
    } catch (Exception e) {
        listener.onFailure(e);
        return;
    }

    executionService.execute(simulateRequest, listener);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:SimulatePipelineTransportAction.java

示例7: testThrowableToAndFromXContent

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
public void testThrowableToAndFromXContent() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();

    final Tuple<Throwable, ElasticsearchException> exceptions = randomExceptions();
    final Throwable throwable = exceptions.v1();

    BytesReference throwableBytes = XContentHelper.toXContent((builder, params) -> {
        ElasticsearchException.generateThrowableXContent(builder, params, throwable);
        return builder;
    }, xContent.type(), randomBoolean());

    ElasticsearchException parsedException;
    try (XContentParser parser = createParser(xContent, throwableBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        parsedException = ElasticsearchException.fromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertDeepEquals(exceptions.v2(), parsedException);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:21,代码来源:ElasticsearchExceptionTests.java

示例8: testUnknownFailureToAndFromXContent

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
public void testUnknownFailureToAndFromXContent() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();

    BytesReference failureBytes = XContentHelper.toXContent((builder, params) -> {
        // Prints a null failure using generateFailureXContent()
        ElasticsearchException.generateFailureXContent(builder, params, null, randomBoolean());
        return builder;
    }, xContent.type(), randomBoolean());

    ElasticsearchException parsedFailure;
    try (XContentParser parser = createParser(xContent, failureBytes)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
        parsedFailure = ElasticsearchException.failureFromXContent(parser);
        assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
        assertNull(parser.nextToken());
    }

    // Failure was null, expecting a "unknown" reason
    assertEquals("Elasticsearch exception [type=exception, reason=unknown]", parsedFailure.getMessage());
    assertEquals(0, parsedFailure.getHeaders().size());
    assertEquals(0, parsedFailure.getMetadata().size());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:ElasticsearchExceptionTests.java

示例9: testCancellationDuringQueryPhase

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
public void testCancellationDuringQueryPhase() throws Exception {

        List<ScriptedBlockPlugin> plugins = initBlockFactory();
        indexTestData();

        logger.info("Executing search");
        ListenableActionFuture<SearchResponse> searchResponse = client().prepareSearch("test").setQuery(
            scriptQuery(new Script(
                ScriptType.INLINE, "native", NativeTestScriptedBlockFactory.TEST_NATIVE_BLOCK_SCRIPT, Collections.emptyMap())))
            .execute();

        awaitForBlock(plugins);
        cancelSearch(SearchAction.NAME);
        disableBlocks(plugins);
        logger.info("Segments {}", XContentHelper.toString(client().admin().indices().prepareSegments("test").get(), FORMAT_PARAMS));
        ensureSearchWasCancelled(searchResponse);
    }
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:SearchCancellationIT.java

示例10: testCancellationDuringFetchPhase

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
public void testCancellationDuringFetchPhase() throws Exception {

        List<ScriptedBlockPlugin> plugins = initBlockFactory();
        indexTestData();

        logger.info("Executing search");
        ListenableActionFuture<SearchResponse> searchResponse = client().prepareSearch("test")
            .addScriptField("test_field",
                new Script(ScriptType.INLINE, "native", NativeTestScriptedBlockFactory.TEST_NATIVE_BLOCK_SCRIPT, Collections.emptyMap())
            ).execute();

        awaitForBlock(plugins);
        cancelSearch(SearchAction.NAME);
        disableBlocks(plugins);
        logger.info("Segments {}", XContentHelper.toString(client().admin().indices().prepareSegments("test").get(), FORMAT_PARAMS));
        ensureSearchWasCancelled(searchResponse);
    }
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:SearchCancellationIT.java

示例11: testParser

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
public void testParser() throws IOException {
    ContextParser<Void, PipelineConfiguration> parser = PipelineConfiguration.getParser();
    XContentType xContentType = randomFrom(XContentType.values());
    final BytesReference bytes;
    try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) {
        new PipelineConfiguration("1", new BytesArray("{}".getBytes(StandardCharsets.UTF_8)), XContentType.JSON)
            .toXContent(builder, ToXContent.EMPTY_PARAMS);
        bytes = builder.bytes();
    }

    XContentParser xContentParser = xContentType.xContent().createParser(NamedXContentRegistry.EMPTY, bytes);
    PipelineConfiguration parsed = parser.parse(xContentParser, null);
    assertEquals(xContentType, parsed.getXContentType());
    assertEquals("{}", XContentHelper.convertToJson(parsed.getConfig(), false, parsed.getXContentType()));
    assertEquals("1", parsed.getId());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:PipelineConfigurationTests.java

示例12: testCheckpointsAdvance

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
public void testCheckpointsAdvance() throws Exception {
    try (ReplicationGroup shards = createGroup(randomInt(3))) {
        shards.startPrimary();
        int numDocs = 0;
        int startedShards;
        do {
            numDocs += shards.indexDocs(randomInt(20));
            startedShards = shards.startReplicas(randomIntBetween(1, 2));
        } while (startedShards > 0);

        if (numDocs == 0 || randomBoolean()) {
            // in the case we have no indexing, we simulate the background global checkpoint sync
            shards.getPrimary().updateGlobalCheckpointOnPrimary();
        }
        for (IndexShard shard : shards) {
            final SeqNoStats shardStats = shard.seqNoStats();
            final ShardRouting shardRouting = shard.routingEntry();
            logger.debug("seq_no stats for {}: {}", shardRouting, XContentHelper.toString(shardStats,
                new ToXContent.MapParams(Collections.singletonMap("pretty", "false"))));
            assertThat(shardRouting + " local checkpoint mismatch", shardStats.getLocalCheckpoint(), equalTo(numDocs - 1L));

            assertThat(shardRouting + " global checkpoint mismatch", shardStats.getGlobalCheckpoint(), equalTo(numDocs - 1L));
            assertThat(shardRouting + " max seq no mismatch", shardStats.getMaxSeqNo(), equalTo(numDocs - 1L));
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:27,代码来源:IndexLevelReplicationTests.java

示例13: testIncludingObjectWithNestedIncludedObject

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
@SuppressWarnings({"unchecked"})
public void testIncludingObjectWithNestedIncludedObject() throws Exception {
    XContentBuilder builder = XContentFactory.jsonBuilder().startObject()
            .startObject("obj1")
            .startObject("obj2")
            .endObject()
            .endObject()
            .endObject();

    Tuple<XContentType, Map<String, Object>> mapTuple = XContentHelper.convertToMap(builder.bytes(), true, builder.contentType());
    Map<String, Object> filteredSource = XContentMapValues.filter(mapTuple.v2(), new String[]{"*.obj2"}, Strings.EMPTY_ARRAY);

    assertThat(filteredSource.size(), equalTo(1));
    assertThat(filteredSource, hasKey("obj1"));
    assertThat(((Map) filteredSource.get("obj1")).size(), equalTo(1));
    assertThat(((Map<String, Object>) filteredSource.get("obj1")), hasKey("obj2"));
    assertThat(((Map) ((Map) filteredSource.get("obj1")).get("obj2")).size(), equalTo(0));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:XContentMapValuesTests.java

示例14: testPutIndexTemplateRequestSerializationXContent

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
public void testPutIndexTemplateRequestSerializationXContent() throws IOException {
    PutIndexTemplateRequest request = new PutIndexTemplateRequest("foo");
    String mapping = YamlXContent.contentBuilder().startObject().field("foo", "bar").endObject().string();
    request.patterns(Collections.singletonList("foo"));
    request.mapping("bar", mapping, XContentType.YAML);
    assertNotEquals(mapping, request.mappings().get("bar"));
    assertEquals(XContentHelper.convertToJson(new BytesArray(mapping), false, XContentType.YAML), request.mappings().get("bar"));

    BytesStreamOutput out = new BytesStreamOutput();
    request.writeTo(out);

    StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes);
    PutIndexTemplateRequest serialized = new PutIndexTemplateRequest();
    serialized.readFrom(in);
    assertEquals(XContentHelper.convertToJson(new BytesArray(mapping), false, XContentType.YAML), serialized.mappings().get("bar"));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:PutIndexTemplateRequestTests.java

示例15: testTaskInfoToString

import org.elasticsearch.common.xcontent.XContentHelper; //导入依赖的package包/类
public void testTaskInfoToString() {
    String nodeId = randomAsciiOfLength(10);
    long taskId = randomIntBetween(0, 100000);
    long startTime = randomNonNegativeLong();
    long runningTime = randomNonNegativeLong();
    boolean cancellable = randomBoolean();
    TaskInfo taskInfo = new TaskInfo(new TaskId(nodeId, taskId), "test_type",
        "test_action", "test_description", null, startTime, runningTime, cancellable, TaskId.EMPTY_TASK_ID);
    String taskInfoString = taskInfo.toString();
    Map<String, Object> map = XContentHelper.convertToMap(new BytesArray(taskInfoString.getBytes(StandardCharsets.UTF_8)), true).v2();
    assertEquals(((Number)map.get("id")).longValue(), taskId);
    assertEquals(map.get("type"), "test_type");
    assertEquals(map.get("action"), "test_action");
    assertEquals(map.get("description"), "test_description");
    assertEquals(((Number)map.get("start_time_in_millis")).longValue(), startTime);
    assertEquals(((Number)map.get("running_time_in_nanos")).longValue(), runningTime);
    assertEquals(map.get("cancellable"), cancellable);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:TaskTests.java


注:本文中的org.elasticsearch.common.xcontent.XContentHelper类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。