本文整理汇总了Java中org.elasticsearch.common.xcontent.XContentParser类的典型用法代码示例。如果您正苦于以下问题:Java XContentParser类的具体用法?Java XContentParser怎么用?Java XContentParser使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
XContentParser类属于org.elasticsearch.common.xcontent包,在下文中一共展示了XContentParser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: parse
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {
ValuesSourceParser<ValuesSource.GeoPoint> vsParser = ValuesSourceParser.geoPoint(aggregationName, InternalGeoCentroid.TYPE, context)
.targetValueType(ValueType.GEOPOINT)
.formattable(true)
.build();
XContentParser.Token token;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (vsParser.token(currentFieldName, token, parser)) {
continue;
} else {
throw new SearchParseException(context, "Unknown key for a " + token + " in aggregation [" + aggregationName + "]: ["
+ currentFieldName + "].", parser.getTokenLocation());
}
}
return new GeoCentroidAggregator.Factory(aggregationName, vsParser.config());
}
示例2: read
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
/**
* Reads the state from a given file and compares the expected version against the actual version of
* the state.
*/
public final T read(Path file) throws IOException {
try (Directory dir = newDirectory(file.getParent())) {
try (final IndexInput indexInput = dir.openInput(file.getFileName().toString(), IOContext.DEFAULT)) {
// We checksum the entire file before we even go and parse it. If it's corrupted we barf right here.
CodecUtil.checksumEntireFile(indexInput);
CodecUtil.checkHeader(indexInput, STATE_FILE_CODEC, STATE_FILE_VERSION, STATE_FILE_VERSION);
final XContentType xContentType = XContentType.values()[indexInput.readInt()];
indexInput.readLong(); // version currently unused
long filePointer = indexInput.getFilePointer();
long contentSize = indexInput.length() - CodecUtil.footerLength() - filePointer;
try (IndexInput slice = indexInput.slice("state_xcontent", filePointer, contentSize)) {
try (XContentParser parser = XContentFactory.xContent(xContentType).createParser(new InputStreamIndexInput(slice, contentSize))) {
return fromXContent(parser);
}
}
} catch(CorruptIndexException | IndexFormatTooOldException | IndexFormatTooNewException ex) {
// we trick this into a dedicated exception with the original stacktrace
throw new CorruptStateException(ex);
}
}
}
示例3: serializeValue
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, XContentParser parser, String fieldName) throws IOException {
sb.setLength(0);
for (String pathEle : path) {
sb.append(pathEle).append('.');
}
sb.append(fieldName);
String key = sb.toString();
String currentValue = parser.text();
String previousValue = settings.put(key, currentValue);
if (previousValue != null) {
throw new ElasticsearchParseException(
"duplicate settings key [{}] found at line number [{}], column number [{}], previous value [{}], current value [{}]",
key,
parser.getTokenLocation().lineNumber,
parser.getTokenLocation().columnNumber,
previousValue,
currentValue
);
}
}
示例4: testToAndFromXContent
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
public void testToAndFromXContent() throws Exception {
XContentType xContentType = randomFrom(XContentType.values());
Tuple<GetResult, GetResult> tuple = randomGetResult(xContentType);
GetResult getResult = tuple.v1();
GetResult expectedGetResult = tuple.v2();
boolean humanReadable = randomBoolean();
BytesReference originalBytes = toXContent(getResult, xContentType, humanReadable);
//test that we can parse what we print out
GetResult parsedGetResult;
try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) {
parsedGetResult = GetResult.fromXContent(parser);
assertNull(parser.nextToken());
}
assertEquals(expectedGetResult, parsedGetResult);
//print the parsed object out and test that the output is the same as the original output
BytesReference finalBytes = toXContent(parsedGetResult, xContentType, humanReadable);
assertToXContentEquivalent(originalBytes, finalBytes, xContentType);
//check that the source stays unchanged, no shuffling of keys nor anything like that
assertEquals(expectedGetResult.sourceAsString(), parsedGetResult.sourceAsString());
}
示例5: testParseInvalidPoint
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
public void testParseInvalidPoint() throws IOException {
// test case 1: create an invalid point object with multipoint data format
XContentBuilder invalidPoint1 = XContentFactory.jsonBuilder()
.startObject()
.field("type", "point")
.startArray("coordinates")
.startArray().value(-74.011).value(40.753).endArray()
.endArray()
.endObject();
XContentParser parser = createParser(invalidPoint1);
parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
// test case 2: create an invalid point object with an empty number of coordinates
XContentBuilder invalidPoint2 = XContentFactory.jsonBuilder()
.startObject()
.field("type", "point")
.startArray("coordinates")
.endArray()
.endObject();
parser = createParser(invalidPoint2);
parser.nextToken();
ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
示例6: parseVariable
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
private AbstractDistanceScoreFunction parseVariable(String fieldName, XContentParser parser, QueryParseContext parseContext, MultiValueMode mode) throws IOException {
// now, the field must exist, else we cannot read the value for
// the doc later
MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
if (fieldType == null) {
throw new QueryParsingException(parseContext, "unknown field [{}]", fieldName);
}
// dates and time need special handling
parser.nextToken();
if (fieldType instanceof DateFieldMapper.DateFieldType) {
return parseDateVariable(fieldName, parser, parseContext, (DateFieldMapper.DateFieldType) fieldType, mode);
} else if (fieldType instanceof GeoPointFieldMapper.GeoPointFieldType) {
return parseGeoVariable(fieldName, parser, parseContext, (GeoPointFieldMapper.GeoPointFieldType) fieldType, mode);
} else if (fieldType instanceof NumberFieldMapper.NumberFieldType) {
return parseNumberVariable(fieldName, parser, parseContext, (NumberFieldMapper.NumberFieldType) fieldType, mode);
} else {
throw new QueryParsingException(parseContext, "field [{}] is of type [{}], but only numeric types are supported.", fieldName, fieldType);
}
}
示例7: testParseXContentForAnalyzeRequest
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
public void testParseXContentForAnalyzeRequest() throws Exception {
XContentParser content = createParser(XContentFactory.jsonBuilder()
.startObject()
.field("text", "THIS IS A TEST")
.field("tokenizer", "keyword")
.array("filter", "lowercase")
.endObject());
AnalyzeRequest analyzeRequest = new AnalyzeRequest("for test");
RestAnalyzeAction.buildFromContent(content, analyzeRequest);
assertThat(analyzeRequest.text().length, equalTo(1));
assertThat(analyzeRequest.text(), equalTo(new String[]{"THIS IS A TEST"}));
assertThat(analyzeRequest.tokenizer().name, equalTo("keyword"));
assertThat(analyzeRequest.tokenFilters().size(), equalTo(1));
for (AnalyzeRequest.NameOrDefinition filter : analyzeRequest.tokenFilters()) {
assertThat(filter.name, equalTo("lowercase"));
}
}
示例8: add
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
public MultiGetRequest add(@Nullable String defaultIndex, @Nullable String defaultType, @Nullable String[] defaultFields,
@Nullable FetchSourceContext defaultFetchSource, @Nullable String defaultRouting, XContentParser parser,
boolean allowExplicitIndex) throws IOException {
XContentParser.Token token;
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
if ("docs".equals(currentFieldName)) {
parseDocuments(parser, this.items, defaultIndex, defaultType, defaultFields, defaultFetchSource, defaultRouting, allowExplicitIndex);
} else if ("ids".equals(currentFieldName)) {
parseIds(parser, this.items, defaultIndex, defaultType, defaultFields, defaultFetchSource, defaultRouting);
}
}
}
return this;
}
示例9: fromXContent
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
public static WrapperQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[wrapper] query malformed");
}
String fieldName = parser.currentName();
if (! QUERY_FIELD.match(fieldName)) {
throw new ParsingException(parser.getTokenLocation(), "[wrapper] query malformed, expected `query` but was " + fieldName);
}
parser.nextToken();
byte[] source = parser.binaryValue();
parser.nextToken();
if (source == null) {
throw new ParsingException(parser.getTokenLocation(), "wrapper query has no [query] specified");
}
return new WrapperQueryBuilder(source);
}
示例10: extractFieldAndBoost
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
private void extractFieldAndBoost(QueryParseContext parseContext, XContentParser parser, Map<String, Float> fieldNameWithBoosts) throws IOException {
String fField = null;
Float fBoost = null;
char[] fieldText = parser.textCharacters();
int end = parser.textOffset() + parser.textLength();
for (int i = parser.textOffset(); i < end; i++) {
if (fieldText[i] == '^') {
int relativeLocation = i - parser.textOffset();
fField = new String(fieldText, parser.textOffset(), relativeLocation);
fBoost = Float.parseFloat(new String(fieldText, i + 1, parser.textLength() - relativeLocation - 1));
break;
}
}
if (fField == null) {
fField = parser.text();
}
if (Regex.isSimpleMatchPattern(fField)) {
for (String field : parseContext.mapperService().simpleMatchToIndexNames(fField)) {
fieldNameWithBoosts.put(field, fBoost);
}
} else {
fieldNameWithBoosts.put(fField, fBoost);
}
}
示例11: parseSpecial
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
@Override
public void parseSpecial(String aggregationName, XContentParser parser, SearchContext context, XContentParser.Token token, String currentFieldName) throws IOException {
if (token == XContentParser.Token.START_OBJECT) {
SignificanceHeuristicParser significanceHeuristicParser = significanceHeuristicParserMapper.get(currentFieldName);
if (significanceHeuristicParser != null) {
significanceHeuristic = significanceHeuristicParser.parse(parser, context.parseFieldMatcher(), context);
} else if (context.parseFieldMatcher().match(currentFieldName, BACKGROUND_FILTER)) {
filter = context.queryParserService().parseInnerFilter(parser).query();
} else {
throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
+ currentFieldName + "].", parser.getTokenLocation());
}
} else {
throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName
+ "].", parser.getTokenLocation());
}
}
示例12: parseSuggestContext
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
public static boolean parseSuggestContext(XContentParser parser, MapperService mapperService, String fieldName,
SuggestionSearchContext.SuggestionContext suggestion, ParseFieldMatcher parseFieldMatcher) throws IOException {
if ("analyzer".equals(fieldName)) {
String analyzerName = parser.text();
Analyzer analyzer = mapperService.analysisService().analyzer(analyzerName);
if (analyzer == null) {
throw new IllegalArgumentException("Analyzer [" + analyzerName + "] doesn't exists");
}
suggestion.setAnalyzer(analyzer);
} else if ("field".equals(fieldName)) {
suggestion.setField(parser.text());
} else if ("size".equals(fieldName)) {
suggestion.setSize(parser.intValue());
} else if (parseFieldMatcher.match(fieldName, Fields.SHARD_SIZE)) {
suggestion.setShardSize(parser.intValue());
} else {
return false;
}
return true;
}
示例13: serializeArray
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
private void serializeArray(Map<String, String> settings, StringBuilder sb, List<String> path, XContentParser parser, String fieldName)
throws IOException {
XContentParser.Token token;
int counter = 0;
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
if (token == XContentParser.Token.START_OBJECT) {
serializeObject(settings, sb, path, parser, fieldName + '.' + (counter++));
} else if (token == XContentParser.Token.START_ARRAY) {
serializeArray(settings, sb, path, parser, fieldName + '.' + (counter++));
} else if (token == XContentParser.Token.FIELD_NAME) {
fieldName = parser.currentName();
} else if (token == XContentParser.Token.VALUE_NULL) {
serializeValue(settings, sb, path, parser, fieldName + '.' + (counter++), true);
// ignore
} else {
serializeValue(settings, sb, path, parser, fieldName + '.' + (counter++), false);
}
}
}
示例14: parse
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
/**
* Parses the template query replacing template parameters with provided
* values. Handles both submitting the template as part of the request as
* well as referencing only the template name.
*
* @param parseContext
* parse context containing the templated query.
*/
@Override
@Nullable
public Query parse(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
Template template = parse(parser, parseContext.parseFieldMatcher());
ExecutableScript executable = this.scriptService.executable(template, ScriptContext.Standard.SEARCH, SearchContext.current(), Collections.<String, String>emptyMap());
BytesReference querySource = (BytesReference) executable.run();
try (XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource)) {
final QueryParseContext context = new QueryParseContext(parseContext.index(), parseContext.indexQueryParserService());
context.reset(qSourceParser);
return context.parseInnerQuery();
}
}
示例15: testXContentRoundTrip
import org.elasticsearch.common.xcontent.XContentParser; //导入依赖的package包/类
public void testXContentRoundTrip() throws Exception {
ExtendedBounds orig = randomExtendedBounds();
try (XContentBuilder out = JsonXContent.contentBuilder()) {
out.startObject();
orig.toXContent(out, ToXContent.EMPTY_PARAMS);
out.endObject();
try (XContentParser in = createParser(JsonXContent.jsonXContent, out.bytes())) {
XContentParser.Token token = in.currentToken();
assertNull(token);
token = in.nextToken();
assertThat(token, equalTo(XContentParser.Token.START_OBJECT));
token = in.nextToken();
assertThat(token, equalTo(XContentParser.Token.FIELD_NAME));
assertThat(in.currentName(), equalTo(ExtendedBounds.EXTENDED_BOUNDS_FIELD.getPreferredName()));
ExtendedBounds read = ExtendedBounds.PARSER.apply(in, null);
assertEquals(orig, read);
} catch (Exception e) {
throw new Exception("Error parsing [" + out.bytes().utf8ToString() + "]", e);
}
}
}