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


Java XContentType类代码示例

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


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

示例1: ClientYamlTestResponse

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
ClientYamlTestResponse(Response response) throws IOException {
    this.response = response;
    if (response.getEntity() != null) {
        String contentType = response.getHeader("Content-Type");
        this.bodyContentType = XContentType.fromMediaTypeOrFormat(contentType);
        try {
            byte[] bytes = EntityUtils.toByteArray(response.getEntity());
            //skip parsing if we got text back (e.g. if we called _cat apis)
            if (bodyContentType != null) {
                this.parsedResponse = ObjectPath.createFromXContent(bodyContentType.xContent(), new BytesArray(bytes));
            }
            this.body = bytes;
        } catch (IOException e) {
            EntityUtils.consumeQuietly(response.getEntity());
            throw e;
        }
    } else {
        this.body = null;
        this.bodyContentType = null;
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:22,代码来源:ClientYamlTestResponse.java

示例2: indexJSONTableDocuments

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
private void indexJSONTableDocuments(TransportClient client, String indexName, String typeName, String tablePath, String... fields) {

        loginTestUser(TEST_USER_NAME, TEST_USER_GROUP);

        // Create an OJAI connection to MapR cluster
        Connection connection = DriverManager.getConnection(CONNECTION_URL);

        // Get an instance of OJAI DocumentStore
        final DocumentStore store = connection.getStore(tablePath);

        DocumentStream documentStream = store.find(fields);
        for (Document document : documentStream) {

            IndexResponse response = client.prepareIndex(indexName, typeName, document.getId().getString())
                    .setSource(document.asJsonString(), XContentType.JSON)
                    .get();

            log.info("Elasticsearch Index Response: '{}'", response);
        }

        // Close this instance of OJAI DocumentStore
        store.close();

        // Close the OJAI connection and release any resources held by the connection
        connection.close();
    }
 
开发者ID:mapr-demos,项目名称:mapr-music,代码行数:27,代码来源:MaprMusicElasticSearchService.java

示例3: testSimpleBulk4

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
public void testSimpleBulk4() throws Exception {
    String bulkAction = copyToStringFromClasspath("/org/elasticsearch/action/bulk/simple-bulk4.json");
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, null, XContentType.JSON);
    assertThat(bulkRequest.numberOfActions(), equalTo(4));
    assertThat(((UpdateRequest) bulkRequest.requests().get(0)).id(), equalTo("1"));
    assertThat(((UpdateRequest) bulkRequest.requests().get(0)).retryOnConflict(), equalTo(2));
    assertThat(((UpdateRequest) bulkRequest.requests().get(0)).doc().source().utf8ToString(), equalTo("{\"field\":\"value\"}"));
    assertThat(((UpdateRequest) bulkRequest.requests().get(1)).id(), equalTo("0"));
    assertThat(((UpdateRequest) bulkRequest.requests().get(1)).type(), equalTo("type1"));
    assertThat(((UpdateRequest) bulkRequest.requests().get(1)).index(), equalTo("index1"));
    Script script = ((UpdateRequest) bulkRequest.requests().get(1)).script();
    assertThat(script, notNullValue());
    assertThat(script.getIdOrCode(), equalTo("counter += param1"));
    assertThat(script.getLang(), equalTo("javascript"));
    Map<String, Object> scriptParams = script.getParams();
    assertThat(scriptParams, notNullValue());
    assertThat(scriptParams.size(), equalTo(1));
    assertThat(((Integer) scriptParams.get("param1")), equalTo(1));
    assertThat(((UpdateRequest) bulkRequest.requests().get(1)).upsertRequest().source().utf8ToString(), equalTo("{\"counter\":1}"));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:22,代码来源:BulkRequestTests.java

示例4: testFromXContent

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
public void testFromXContent() throws Exception {
    for (int runs = 0; runs < 20; runs++) {
        SearchAfterBuilder searchAfterBuilder = randomJsonSearchFromBuilder();
        XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
        if (randomBoolean()) {
            builder.prettyPrint();
        }
        builder.startObject();
        searchAfterBuilder.innerToXContent(builder);
        builder.endObject();
        XContentParser parser = createParser(shuffleXContent(builder));
        parser.nextToken();
        parser.nextToken();
        parser.nextToken();
        SearchAfterBuilder secondSearchAfterBuilder = SearchAfterBuilder.fromXContent(parser);
        assertNotSame(searchAfterBuilder, secondSearchAfterBuilder);
        assertEquals(searchAfterBuilder, secondSearchAfterBuilder);
        assertEquals(searchAfterBuilder.hashCode(), secondSearchAfterBuilder.hashCode());
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:21,代码来源:SearchAfterBuilderTests.java

示例5: testFromXContent

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
public void testFromXContent() throws IOException {
    SearchSortValues sortValues = createTestItem();
    XContentType xcontentType = randomFrom(XContentType.values());
    boolean humanReadable = randomBoolean();
    BytesReference originalBytes = toXContent(sortValues, xcontentType, humanReadable);

    SearchSortValues parsed;
    try (XContentParser parser = createParser(xcontentType.xContent(), originalBytes)) {
        parser.nextToken(); // skip to the elements start array token, fromXContent advances from there if called
        parser.nextToken();
        parser.nextToken();
        parsed = SearchSortValues.fromXContent(parser);
        parser.nextToken();
        assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken());
        assertNull(parser.nextToken());
    }
    assertToXContentEquivalent(originalBytes, toXContent(parsed, xcontentType, humanReadable), xcontentType);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:SearchSortValuesTests.java

示例6: testEmptySimpleQueryStringWithAnalysis

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
public void testEmptySimpleQueryStringWithAnalysis() throws Exception {
    // https://github.com/elastic/elasticsearch/issues/18202
    String mapping = XContentFactory.jsonBuilder()
            .startObject()
            .startObject("type1")
            .startObject("properties")
            .startObject("body")
            .field("type", "text")
            .field("analyzer", "stop")
            .endObject()
            .endObject()
            .endObject()
            .endObject().string();

    CreateIndexRequestBuilder mappingRequest = client().admin().indices()
            .prepareCreate("test1")
            .addMapping("type1", mapping, XContentType.JSON);
    mappingRequest.execute().actionGet();
    indexRandom(true, client().prepareIndex("test1", "type1", "1").setSource("body", "Some Text"));
    refresh();

    SearchResponse searchResponse = client().prepareSearch()
            .setQuery(simpleQueryStringQuery("the*").field("body")).get();
    assertNoFailures(searchResponse);
    assertHitCount(searchResponse, 0L);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:27,代码来源:SimpleQueryStringIT.java

示例7: testToAndFromXContent

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
public void testToAndFromXContent() throws Exception {
    XContentType xContentType = randomFrom(XContentType.values());
    Tuple<GetField, GetField> tuple = randomGetField(xContentType);
    GetField getField = tuple.v1();
    GetField expectedGetField = tuple.v2();
    boolean humanReadable = randomBoolean();
    BytesReference originalBytes = toXContent(getField, xContentType, humanReadable);
    //test that we can parse what we print out
    GetField parsedGetField;
    try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
        //we need to move to the next token, the start object one that we manually added is not expected
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
        parsedGetField = GetField.fromXContent(parser);
        assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken());
        assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken());
        assertNull(parser.nextToken());
    }
    assertEquals(expectedGetField, parsedGetField);
    BytesReference finalBytes = toXContent(parsedGetField, xContentType, humanReadable);
    assertToXContentEquivalent(originalBytes, finalBytes, xContentType);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:23,代码来源:GetFieldTests.java

示例8: testFromXContent

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
/**
 *  creates random highlighter, renders it to xContent and back to new instance that should be equal to original
 */
public void testFromXContent() throws IOException {
    for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) {
        HighlightBuilder highlightBuilder = randomHighlighterBuilder();
        XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
        if (randomBoolean()) {
            builder.prettyPrint();
        }
        highlightBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS);
        XContentBuilder shuffled = shuffleXContent(builder);

        XContentParser parser = createParser(shuffled);
        QueryParseContext context = new QueryParseContext(parser);
        parser.nextToken();
        HighlightBuilder secondHighlightBuilder;
        try {
            secondHighlightBuilder = HighlightBuilder.fromXContent(context);
        } catch (RuntimeException e) {
            throw new RuntimeException("Error parsing " + highlightBuilder, e);
        }
        assertNotSame(highlightBuilder, secondHighlightBuilder);
        assertEquals(highlightBuilder, secondHighlightBuilder);
        assertEquals(highlightBuilder.hashCode(), secondHighlightBuilder.hashCode());
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:28,代码来源:HighlightBuilderTests.java

示例9: testValidate

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
public void testValidate() throws Exception {
    PutPipelineRequest putRequest = new PutPipelineRequest("_id", new BytesArray(
            "{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\", \"tag\": \"tag1\"}}," +
                "{\"remove\" : {\"field\": \"_field\", \"tag\": \"tag2\"}}]}"),
        XContentType.JSON);

    DiscoveryNode node1 = new DiscoveryNode("_node_id1", buildNewFakeTransportAddress(),
            emptyMap(), emptySet(), Version.CURRENT);
    DiscoveryNode node2 = new DiscoveryNode("_node_id2", buildNewFakeTransportAddress(),
            emptyMap(), emptySet(), Version.CURRENT);
    Map<DiscoveryNode, IngestInfo> ingestInfos = new HashMap<>();
    ingestInfos.put(node1, new IngestInfo(Arrays.asList(new ProcessorInfo("set"), new ProcessorInfo("remove"))));
    ingestInfos.put(node2, new IngestInfo(Arrays.asList(new ProcessorInfo("set"))));

    ElasticsearchParseException e =
        expectThrows(ElasticsearchParseException.class, () -> store.validatePipeline(ingestInfos, putRequest));
    assertEquals("Processor type [remove] is not installed on node [" + node2 + "]", e.getMessage());
    assertEquals("remove", e.getHeader("processor_type").get(0));
    assertEquals("tag2", e.getHeader("processor_tag").get(0));

    ingestInfos.put(node2, new IngestInfo(Arrays.asList(new ProcessorInfo("set"), new ProcessorInfo("remove"))));
    store.validatePipeline(ingestInfos, putRequest);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:PipelineStoreTests.java

示例10: testItemSerializationBwc

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
public void testItemSerializationBwc() throws IOException {
    final byte[] data = Base64.getDecoder().decode("AQVpbmRleAEEdHlwZQEODXsiZm9vIjoiYmFyIn0A/wD//////////QAAAAAAAAAA");
    final Version version = randomFrom(Version.V_5_0_0, Version.V_5_0_1, Version.V_5_0_2,
        Version.V_5_0_3_UNRELEASED, Version.V_5_1_1_UNRELEASED, Version.V_5_1_2_UNRELEASED, Version.V_5_2_0_UNRELEASED);
    try (StreamInput in = StreamInput.wrap(data)) {
        in.setVersion(version);
        Item item = new Item(in);
        assertEquals(XContentType.JSON, item.xContentType());
        assertEquals("{\"foo\":\"bar\"}", item.doc().utf8ToString());
        assertEquals("index", item.index());
        assertEquals("type", item.type());

        try (BytesStreamOutput out = new BytesStreamOutput()) {
            out.setVersion(version);
            item.writeTo(out);
            assertArrayEquals(data, out.bytes().toBytesRef().bytes);
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:20,代码来源:MoreLikeThisQueryBuilderTests.java

示例11: testUpdateMappingWithoutTypeMultiObjects

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
public void testUpdateMappingWithoutTypeMultiObjects() throws Exception {
    client().admin().indices().prepareCreate("test")
            .setSettings(
                    Settings.builder()
                            .put("index.number_of_shards", 1)
                            .put("index.number_of_replicas", 0)
            ).execute().actionGet();
    client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet();

    PutMappingResponse putMappingResponse = client().admin().indices().preparePutMapping("test").setType("doc")
            .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}", XContentType.JSON)
            .execute().actionGet();

    assertThat(putMappingResponse.isAcknowledged(), equalTo(true));

    GetMappingsResponse getMappingsResponse = client().admin().indices().prepareGetMappings("test").execute().actionGet();
    assertThat(getMappingsResponse.mappings().get("test").get("doc").source().toString(),
            equalTo("{\"doc\":{\"properties\":{\"date\":{\"type\":\"integer\"}}}}"));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:20,代码来源:UpdateMappingIntegrationIT.java

示例12: readFrom

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
@Override
public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    type = in.readOptionalString();
    id = in.readOptionalString();
    routing = in.readOptionalString();
    parent = in.readOptionalString();
    if (in.getVersion().before(Version.V_6_0_0_alpha1_UNRELEASED)) {
        in.readOptionalString(); // timestamp
        in.readOptionalWriteable(TimeValue::new); // ttl
    }
    source = in.readBytesReference();
    opType = OpType.fromId(in.readByte());
    version = in.readLong();
    versionType = VersionType.fromValue(in.readByte());
    pipeline = in.readOptionalString();
    isRetry = in.readBoolean();
    autoGeneratedTimestamp = in.readLong();
    if (in.getVersion().onOrAfter(Version.V_5_3_0_UNRELEASED)) {
        contentType = in.readOptionalWriteable(XContentType::readFrom);
    } else {
        contentType = XContentFactory.xContentType(source);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:IndexRequest.java

示例13: testEnforceSameContentType

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
public void testEnforceSameContentType() {
    XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE);
    IndexRequest indexRequest = new IndexRequest().source(singletonMap("field", "value"), xContentType);
    assertEquals(xContentType, enforceSameContentType(indexRequest, null));
    assertEquals(xContentType, enforceSameContentType(indexRequest, xContentType));

    XContentType bulkContentType = randomBoolean() ? xContentType : null;

    IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () ->
            enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), XContentType.CBOR), bulkContentType));
    assertEquals("Unsupported content-type found for request with content-type [CBOR], only JSON and SMILE are supported",
            exception.getMessage());

    exception = expectThrows(IllegalArgumentException.class, () ->
            enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), XContentType.YAML), bulkContentType));
    assertEquals("Unsupported content-type found for request with content-type [YAML], only JSON and SMILE are supported",
            exception.getMessage());

    XContentType requestContentType = xContentType == XContentType.JSON ? XContentType.SMILE : XContentType.JSON;

    exception = expectThrows(IllegalArgumentException.class, () ->
            enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), requestContentType), xContentType));
    assertEquals("Mismatching content-type found for request with content-type [" + requestContentType + "], "
            + "previous requests have content-type [" + xContentType + "]", exception.getMessage());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:26,代码来源:RequestTests.java

示例14: indexDoc

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
protected Engine.Index indexDoc(IndexShard shard, String type, String id, String source, XContentType xContentType) throws IOException {
    final Engine.Index index;
    if (shard.routingEntry().primary()) {
        index = shard.prepareIndexOnPrimary(
            SourceToParse.source(SourceToParse.Origin.PRIMARY, shard.shardId().getIndexName(), type, id, new BytesArray(source),
                xContentType),
            Versions.MATCH_ANY,
            VersionType.INTERNAL,
            IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP,
            false);
    } else {
        index = shard.prepareIndexOnReplica(
            SourceToParse.source(SourceToParse.Origin.PRIMARY, shard.shardId().getIndexName(), type, id, new BytesArray(source),
                xContentType),
            randomInt(1 << 10), 1, VersionType.EXTERNAL, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false);
    }
    shard.index(index);
    return index;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:20,代码来源:IndexShardTestCase.java

示例15: testBuildRequestThrowsException

import org.elasticsearch.common.xcontent.XContentType; //导入依赖的package包/类
/**
 * Mimicks script failures or general wrongness by implementers.
 */
public void testBuildRequestThrowsException() throws Exception {
    DummyAsyncBulkByScrollAction action = new DummyAsyncBulkByScrollAction() {
        @Override
        protected AbstractAsyncBulkByScrollAction.RequestWrapper<?> buildRequest(Hit doc) {
            throw new RuntimeException("surprise");
        }
    };
    ScrollableHitSource.BasicHit hit = new ScrollableHitSource.BasicHit("index", "type", "id", 0);
    hit.setSource(new BytesArray("{}"), XContentType.JSON);
    ScrollableHitSource.Response response = new ScrollableHitSource.Response(false, emptyList(), 1, singletonList(hit), null);
    simulateScrollResponse(action, timeValueNanos(System.nanoTime()), 0, response);
    ExecutionException e = expectThrows(ExecutionException.class, () -> listener.get());
    assertThat(e.getCause(), instanceOf(RuntimeException.class));
    assertThat(e.getCause().getMessage(), equalTo("surprise"));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:AsyncBulkByScrollActionTests.java


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