i found some examples how to use XContentBuilder in Elasticsearch 7.x but these examples do not work any more since ESJAC is completely new programmed. But as XContentBuilder still exists: XContentBuilder (elasticsearch-x-content 8.1.0 API)
i wonder if there are any working examples out there.
org.elasticsearch.xcontent.XContentBuilder xcb = XContentFactory.jsonBuilder();
xcb.startObject();
{
xcb.startObject("properties");
{
xcb.startObject("Rechnungsdatum");
{
xcb.field("type", "date");
}
xcb.endObject();
}
xcb.endObject();
}
xcb.endObject();
ByteArrayOutputStream baos = (ByteArrayOutputStream) xcb.getOutputStream();
byte[] bytes = baos.toByteArray();
System.out.println("b:" + bytes[0]);
InputStream is = new ByteArrayInputStream(bytes);
SourceField sf = new SourceField.Builder().withJson(is).build();
PutMappingRequest pmr2 = new PutMappingRequest.Builder().index("rechnungen4").source(sf).build();
client.indices().putMapping(pmr2);
But in the Line of the sysout the bytes-Array is already empty, which leads to a jakarta.json.JsonException: Cannot auto-detect encoding, not enough chars.
{"properties":{"Rechnungsdatum":{"type":"date"}}}
Exception in thread "main" co.elastic.clients.json.JsonpMappingException: Error deserializing co.elastic.clients.elastic
search._types.mapping.SourceField: Unknown field 'properties' (JSON path: properties) (line no=1, column no=14, offset=1
3)
at co.elastic.clients.json.ObjectDeserializer.parseUnknownField(ObjectDeserializer.java:221)
at co.elastic.clients.json.ObjectDeserializer.deserialize(ObjectDeserializer.java:178)
at co.elastic.clients.util.WithJsonObjectBuilderBase.withJson(WithJsonObjectBuilderBase.java:54)
at co.elastic.clients.json.WithJson.withJson(WithJson.java:57)
First line shows that JSON is correct. But SourceField seems not to like it. Why does it even care about my JSON? Its correct so just send it! =(
You don't need XContent for what you want to achieve (create an index mapping).
The Java API client offers a fully typed API to create your mappings:
esClient.indices().putMapping(m -> m
.index("rechnungen4")
.properties("Rechnungsdatum", p -> p
.date(d -> d) // d is a DateProperty.Builder on which we don't set any value, keeping all defaults.
)
);
Apache, Apache Lucene, Apache Hadoop, Hadoop, HDFS and the yellow elephant
logo are trademarks of the
Apache Software Foundation
in the United States and/or other countries.