当前位置: 首页>>代码示例>>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;未经允许,请勿转载。