當前位置: 首頁>>代碼示例>>Java>>正文


Java XContentFactory類代碼示例

本文整理匯總了Java中org.elasticsearch.common.xcontent.XContentFactory的典型用法代碼示例。如果您正苦於以下問題:Java XContentFactory類的具體用法?Java XContentFactory怎麽用?Java XContentFactory使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


XContentFactory類屬於org.elasticsearch.common.xcontent包,在下文中一共展示了XContentFactory類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: explain

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
@Override
public String explain() {
    try {
        XContentBuilder firstBuilder = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint();
        firstTable.getRequestBuilder().request().source().toXContent(firstBuilder, ToXContent.EMPTY_PARAMS);

        XContentBuilder secondBuilder = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint();
        secondTable.getRequestBuilder().request().source().toXContent(secondBuilder, ToXContent.EMPTY_PARAMS);
        String explained = String.format(" first query:\n%s\n second query:\n%s", firstBuilder.string(), secondBuilder.string());

        return explained;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
開發者ID:mazhou,項目名稱:es-sql,代碼行數:17,代碼來源:JoinRequestBuilder.java

示例2: testConditionsParsing

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
public void testConditionsParsing() throws Exception {
    final RolloverRequest request = new RolloverRequest(randomAsciiOfLength(10), randomAsciiOfLength(10));
    final XContentBuilder builder = XContentFactory.jsonBuilder()
        .startObject()
            .startObject("conditions")
                .field("max_age", "10d")
                .field("max_docs", 100)
            .endObject()
        .endObject();
    RolloverRequest.PARSER.parse(createParser(builder), request, null);
    Set<Condition> conditions = request.getConditions();
    assertThat(conditions.size(), equalTo(2));
    for (Condition condition : conditions) {
        if (condition instanceof MaxAgeCondition) {
            MaxAgeCondition maxAgeCondition = (MaxAgeCondition) condition;
            assertThat(maxAgeCondition.value.getMillis(), equalTo(TimeValue.timeValueHours(24 * 10).getMillis()));
        } else if (condition instanceof MaxDocsCondition) {
            MaxDocsCondition maxDocsCondition = (MaxDocsCondition) condition;
            assertThat(maxDocsCondition.value, equalTo(100L));
        } else {
            fail("unexpected condition " + condition);
        }
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:25,代碼來源:RolloverRequestTests.java

示例3: testCamelCaseFieldNameStaysAsIs

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
public void testCamelCaseFieldNameStaysAsIs() throws Exception {
    String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
            .endObject().endObject().string();

    IndexService index = createIndex("test");
    client().admin().indices().preparePutMapping("test").setType("type").setSource(mapping, XContentType.JSON).get();
    DocumentMapper documentMapper = index.mapperService().documentMapper("type");

    ParsedDocument doc = documentMapper.parse("test", "type", "1", XContentFactory.jsonBuilder().startObject()
            .field("thisIsCamelCase", "value1")
            .endObject().bytes());

    assertNotNull(doc.dynamicMappingsUpdate());
    client().admin().indices().preparePutMapping("test").setType("type")
        .setSource(doc.dynamicMappingsUpdate().toString(), XContentType.JSON).get();

    documentMapper = index.mapperService().documentMapper("type");
    assertNotNull(documentMapper.mappers().getMapper("thisIsCamelCase"));
    assertNull(documentMapper.mappers().getMapper("this_is_camel_case"));

    documentMapper = index.mapperService().documentMapperParser().parse("type", documentMapper.mappingSource());

    assertNotNull(documentMapper.mappers().getMapper("thisIsCamelCase"));
    assertNull(documentMapper.mappers().getMapper("this_is_camel_case"));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:26,代碼來源:CamelCaseFieldNameTests.java

示例4: testStore

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
public void testStore() throws Exception {
    String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
            .startObject("properties").startObject("field").field("type", "ip").field("store", true).endObject().endObject()
            .endObject().endObject().string();

    DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));

    assertEquals(mapping, mapper.mappingSource().toString());

    ParsedDocument doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
            .startObject()
            .field("field", "::1")
            .endObject()
            .bytes());

    IndexableField[] fields = doc.rootDoc().getFields("field");
    assertEquals(3, fields.length);
    IndexableField pointField = fields[0];
    assertEquals(1, pointField.fieldType().pointDimensionCount());
    IndexableField dvField = fields[1];
    assertEquals(DocValuesType.SORTED_SET, dvField.fieldType().docValuesType());
    IndexableField storedField = fields[2];
    assertTrue(storedField.fieldType().stored());
    assertEquals(new BytesRef(InetAddressPoint.encode(InetAddress.getByName("::1"))),
            storedField.binaryValue());
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:27,代碼來源:IpFieldMapperTests.java

示例5: testFromXContent

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
/**
 *  creates random rescorer, 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++) {
        RescoreBuilder<?> rescoreBuilder = randomRescoreBuilder();
        XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
        if (randomBoolean()) {
            builder.prettyPrint();
        }
        rescoreBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS);
        XContentBuilder shuffled = shuffleXContent(builder);


        XContentParser parser = createParser(shuffled);
        QueryParseContext context = new QueryParseContext(parser);
        parser.nextToken();
        RescoreBuilder<?> secondRescoreBuilder = RescoreBuilder.parseFromXContent(context);
        assertNotSame(rescoreBuilder, secondRescoreBuilder);
        assertEquals(rescoreBuilder, secondRescoreBuilder);
        assertEquals(rescoreBuilder.hashCode(), secondRescoreBuilder.hashCode());
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:24,代碼來源:QueryRescoreBuilderTests.java

示例6: testDynamicDateDetectionEnabledWithNoSpecialCharacters

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
public void testDynamicDateDetectionEnabledWithNoSpecialCharacters() throws IOException {
    DocumentMapperParser mapperParser = createIndex("test").mapperService().documentMapperParser();
    String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
            .startArray("dynamic_date_formats")
                .value("yyyy MM")
            .endArray().endObject().endObject().string();
    DocumentMapper mapper = mapperParser.parse("type", new CompressedXContent(mapping));

    BytesReference bytes = XContentFactory.jsonBuilder()
        .startObject()
            .field("foo", "2016 12")
        .endObject().bytes();

    // We should have generated a date field
    ParsedDocument doc = mapper.parse("test", "type", "1", bytes);
    Mapping update = doc.dynamicMappingsUpdate();
    assertNotNull(update);
    Mapper dateMapper = update.root().getMapper("foo");
    assertNotNull(dateMapper);
    assertThat(dateMapper, instanceOf(DateFieldMapper.class));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:22,代碼來源:DocumentParserTests.java

示例7: testIncludingObjectWithNestedIncludedObject

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的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

示例8: testToXContent

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
public void testToXContent() throws IOException {
    Build build = new Build("buildHash", "2016-11-15".toString(), true);
    Version version = Version.V_2_4_5;
    MainResponse response = new MainResponse("nodeName", version, new ClusterName("clusterName"), "clusterUuid", build, true);
    XContentBuilder builder = XContentFactory.jsonBuilder();
    response.toXContent(builder, ToXContent.EMPTY_PARAMS);
    assertEquals("{"
            + "\"name\":\"nodeName\","
            + "\"cluster_name\":\"clusterName\","
            + "\"cluster_uuid\":\"clusterUuid\","
            + "\"version\":{"
                + "\"number\":\"2.4.5\","
                + "\"build_hash\":\"buildHash\","
                + "\"build_date\":\"2016-11-15\","
                + "\"build_snapshot\":true,"
                + "\"lucene_version\":\"5.5.2\"},"
            + "\"tagline\":\"You Know, for Search\""
      + "}", builder.string());
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:MainResponseTests.java

示例9: parse

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    XContentParser parser = parseContext.parser();

    XContentParser.Token token = parser.nextToken();
    if (token != XContentParser.Token.FIELD_NAME) {
        throw new QueryParsingException(parseContext, "[wrapper] query malformed");
    }
    String fieldName = parser.currentName();
    if (!fieldName.equals("query")) {
        throw new QueryParsingException(parseContext, "[wrapper] query malformed");
    }
    parser.nextToken();

    byte[] querySource = parser.binaryValue();
    try (XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource)) {
        final QueryParseContext context = new QueryParseContext(parseContext.index(), parseContext.indexQueryParserService());
        context.reset(qSourceParser);
        Query result = context.parseInnerQuery();
        parser.nextToken();
        parseContext.combineNamedQueries(context);
        return result;
    }
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:25,代碼來源:WrapperQueryParser.java

示例10: createScript

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
private Script createScript() throws IOException {
    final Map<String, Object> params = randomBoolean() ? Collections.emptyMap() : Collections.singletonMap("key", "value");
    ScriptType scriptType = randomFrom(ScriptType.values());
    String script;
    if (scriptType == ScriptType.INLINE) {
        try (XContentBuilder builder = XContentFactory.jsonBuilder()) {
            builder.startObject();
            builder.field("field", randomAsciiOfLengthBetween(1, 5));
            builder.endObject();
            script = builder.string();
        }
    } else {
        script = randomAsciiOfLengthBetween(1, 5);
    }
    return new Script(
        scriptType,
        scriptType == ScriptType.STORED ? null : randomFrom("_lang1", "_lang2", "_lang3"),
        script,
        scriptType == ScriptType.INLINE ?
                Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) : null, params
    );
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:23,代碼來源:ScriptTests.java

示例11: testEmptyName

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
public void testEmptyName() throws Exception {
    // after 5.x
    String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1")
        .startObject("properties").startObject("").field("type", "percolator").endObject().endObject()
        .endObject().endObject().string();
    DocumentMapperParser parser = mapperService.documentMapperParser();

    IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
        () -> parser.parse("type1", new CompressedXContent(mapping))
    );
    assertThat(e.getMessage(), containsString("name cannot be empty string"));

    // before 5.x
    Version oldVersion = VersionUtils.randomVersionBetween(getRandom(), Version.V_2_0_0, Version.V_2_3_5);
    Settings oldIndexSettings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, oldVersion).build();
    DocumentMapperParser parser2x = createIndex("test_old", oldIndexSettings).mapperService().documentMapperParser();

    DocumentMapper defaultMapper = parser2x.parse("type1", new CompressedXContent(mapping));
    assertEquals(mapping, defaultMapper.mappingSource().string());
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:21,代碼來源:PercolatorFieldMapperTests.java

示例12: testMappingMetaDataParsed

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
public void testMappingMetaDataParsed() throws Exception {
    logger.info("--> starting 1 nodes");
    internalCluster().startNode();

    logger.info("--> creating test index, with meta routing");
    client().admin().indices().prepareCreate("test")
            .addMapping("type1", XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("_routing")
                .field("required", true).endObject().endObject().endObject())
            .execute().actionGet();

    logger.info("--> verify meta _routing required exists");
    MappingMetaData mappingMd = client().admin().cluster().prepareState().execute().actionGet().getState().metaData()
        .index("test").mapping("type1");
    assertThat(mappingMd.routing().required(), equalTo(true));

    logger.info("--> restarting nodes...");
    internalCluster().fullRestart();

    logger.info("--> waiting for yellow status");
    ensureYellow();

    logger.info("--> verify meta _routing required exists");
    mappingMd = client().admin().cluster().prepareState().execute().actionGet().getState().metaData().index("test").mapping("type1");
    assertThat(mappingMd.routing().required(), equalTo(true));
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:26,代碼來源:GatewayIndexStateIT.java

示例13: testNotIndexed

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
public void testNotIndexed() throws Exception {
    String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
            .startObject("properties").startObject("field").field("type", "scaled_float")
            .field("index", false).field("scaling_factor", 10.0).endObject().endObject()
            .endObject().endObject().string();

    DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));

    assertEquals(mapping, mapper.mappingSource().toString());

    ParsedDocument doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
            .startObject()
            .field("field", 123)
            .endObject()
            .bytes());

    IndexableField[] fields = doc.rootDoc().getFields("field");
    assertEquals(1, fields.length);
    IndexableField dvField = fields[0];
    assertEquals(DocValuesType.SORTED_NUMERIC, dvField.fieldType().docValuesType());
    assertEquals(1230, dvField.numericValue().longValue());
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:23,代碼來源:ScaledFloatFieldMapperTests.java

示例14: indexWord

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
@Override
public boolean indexWord(String word) {
	if (bulk == null) {
		bulk = client.prepareBulk();
	}
	try {
		bulk.add(client.prepareIndex(INDEX_NAME, INDEX_TYPE)
				.setSource(XContentFactory.jsonBuilder()
						.startObject()
						.field(FIELD_NAME, word)
						.endObject()));
	} catch (IOException e) {
		// should never happen
		throw new RuntimeException(e);
	}
	return true;
}
 
開發者ID:searchhub,項目名稱:preDict,代碼行數:18,代碼來源:ElasticsearchWordSearch.java

示例15: testFromXContent

import org.elasticsearch.common.xcontent.XContentFactory; //導入依賴的package包/類
/**
 *  creates random candidate generator, 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_RUNS; runs++) {
        DirectCandidateGeneratorBuilder generator = randomCandidateGenerator();
        XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
        if (randomBoolean()) {
            builder.prettyPrint();
        }
        generator.toXContent(builder, ToXContent.EMPTY_PARAMS);
        XContentParser parser = createParser(shuffleXContent(builder));
        parser.nextToken();
        DirectCandidateGeneratorBuilder secondGenerator = DirectCandidateGeneratorBuilder.PARSER.apply(parser, null);
        assertNotSame(generator, secondGenerator);
        assertEquals(generator, secondGenerator);
        assertEquals(generator.hashCode(), secondGenerator.hashCode());
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:20,代碼來源:DirectCandidateGeneratorTests.java


注:本文中的org.elasticsearch.common.xcontent.XContentFactory類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。