# How to use XContentBuilder in Elasticsearch 8.0

**URL:** <https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256>\
**Category:** Elasticsearch\
**Created:** [October 22, 2022, 5:40pm UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256 "2022-10-22T17:40:36Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![Michael\_Gattinger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/michael_gattinger/32/99690_2.png) [@Michael\_Gattinger](https://discuss.elastic.co/u/Michael_Gattinger)\
**Post date:** [October 22, 2022, 5:40pm UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256/1 "2022-10-22T17:40:36Z")

</div>

Hi,

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)](https://javadoc.io/static/org.elasticsearch/elasticsearch-x-content/8.1.0/org/elasticsearch/xcontent/XContentBuilder.html)  
i wonder if there are any working examples out there.

Thanks - Enomine

---

<div class="post-metadata">

**Author:** ![Michael\_Gattinger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/michael_gattinger/32/99690_2.png) [@Michael\_Gattinger](https://discuss.elastic.co/u/Michael_Gattinger)\
**Post date:** [October 22, 2022, 8:37pm UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256/2 "2022-10-22T20:37:42Z")

</div>

Here is what i tried so far:

```auto
		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.

Thanks - Enomine

---

<div class="post-metadata">

**Author:** ![Michael\_Gattinger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/michael_gattinger/32/99690_2.png) [@Michael\_Gattinger](https://discuss.elastic.co/u/Michael_Gattinger)\
**Post date:** [October 22, 2022, 9:04pm UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256/3 "2022-10-22T21:04:55Z")

</div>

Okay so far so good, found this way:

```auto
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();
		String json = Strings.toString(xcb);
		System.out.println(json);
		SourceField sf = new SourceField.Builder().withJson(new StringReader(json)).build();
		PutMappingRequest pmr2 = new PutMappingRequest.Builder().index("rechnungen4").source(sf).build();
		client.indices().putMapping(pmr2);

```

by including an old dependency:

```auto
	<dependency>
      <groupId>org.elasticsearch.client</groupId>
      <artifactId>transport</artifactId>
      <version>7.17.6</version>
	</dependency>

```

But above code results in:

```auto
{"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! =(

Thanks - Enomine

---

<div class="post-metadata">

**Author:** ![Michael\_Gattinger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/michael_gattinger/32/99690_2.png) [@Michael\_Gattinger](https://discuss.elastic.co/u/Michael_Gattinger)\
**Post date:** [October 23, 2022, 2:58am UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256/4 "2022-10-23T02:58:06Z")

</div>

... Still working on that problem.  
Now i figured out a "solution" without an exception but it does nothing to the index because SourceField is empty.

```auto
		XContentBuilder xcb = XContentFactory.jsonBuilder();
		xcb.startObject();
		xcb.startObject("properties");
		xcb.startObject("Rechnungsdatum");
		xcb.field("type", "date");
		xcb.endObject();
		xcb.endObject();
		xcb.endObject();
		String json = Strings.toString(xcb);
		System.out.println(json);
		jakarta.json.stream.JsonParser jp = Json.createParser(new StringReader(json));
		JsonpMapper jm = new JacksonJsonpMapper();
		// jm.ignoreUnknownFields();
		SourceField sf = new SourceField.Builder().withJson(jp, jm).build();
		System.out.println(sf.toString());
		PutMappingRequest pmr2 = new PutMappingRequest.Builder().index("rechnungen4").source(sf).build();
		client.indices().putMapping(pmr2);

```

Thanks - Enomine

---

<div class="post-metadata">

**Author:** ![Michael\_Gattinger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/michael_gattinger/32/99690_2.png) [@Michael\_Gattinger](https://discuss.elastic.co/u/Michael_Gattinger)\
**Post date:** [October 23, 2022, 3:25am UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256/5 "2022-10-23T03:25:25Z")

</div>

Finally i figured it out. Well Elasticsearch is really not beginner friendly!

```auto
GetMappingRequest gmr = new GetMappingRequest.Builder().index("rechnungen5").build();
		GetMappingResponse gma = client.indices().getMapping(gmr);
		System.out.println(gma.toString());

		Map<String, Property> msp = new HashMap<String, Property>();
		msp.put("Rechnungsnummer", new Property.Builder().integer(new IntegerNumberProperty.Builder().build()).build());
		msp.put("Rechnungsbetrag", new Property.Builder().float_(f -> f).build());
		PutMappingRequest pmr = new PutMappingRequest.Builder().index("rechnungen5").properties(msp).build();
		PutMappingResponse pma = client.indices().putMapping(pmr);
		System.out.println(pma.toString());

		gma = client.indices().getMapping(gmr);
		System.out.println(gma.toString());

		XContentBuilder xcb = XContentFactory.jsonBuilder();
		xcb.startObject();
		xcb.startObject("properties");
		xcb.startObject("Rechnungsdatum");
		xcb.field("type", "date");
		xcb.endObject();
		xcb.endObject();
		xcb.endObject();
		String json = Strings.toString(xcb);
		System.out.println(json);
		jakarta.json.stream.JsonParser jp = Json.createParser(new StringReader(json));
		JsonpMapper jm = new JacksonJsonpMapper();
		// jm.ignoreUnknownFields();
		PutMappingRequest pmr2 = new PutMappingRequest.Builder().index("rechnungen5").withJson(jp, jm).build();
		PutMappingResponse pma2 = client.indices().putMapping(pmr2);
		System.out.println(pma2.toString());

		gma = client.indices().getMapping(gmr);
		System.out.println(gma.toString());

```

Thanks - Enomine

---

<div class="post-metadata">

**Author:** ![Michael\_Gattinger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/michael_gattinger/32/99690_2.png) [@Michael\_Gattinger](https://discuss.elastic.co/u/Michael_Gattinger)\
**Post date:** [October 23, 2022, 3:55am UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256/6 "2022-10-23T03:55:35Z")

</div>

And you can get rid of JsonParser and JsonpMapper:

```auto
XContentBuilder xcb = XContentFactory.jsonBuilder();
		xcb.startObject();
		xcb.startObject("properties");
		xcb.startObject("Rechnungsdatum");
		xcb.field("type", "date");
		xcb.endObject();
		xcb.endObject();
		xcb.endObject();
		String json = Strings.toString(xcb);
		System.out.println(json);
		PutMappingRequest pmr2 = new PutMappingRequest.Builder().index("rechnungen7").withJson(new StringReader(json)).build();
		PutMappingResponse pma2 = client.indices().putMapping(pmr2);
		System.out.println(pma2.toString());

```

Thanks - Enomine

---

<div class="post-metadata">

**Author:** ![Michael\_Gattinger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/michael_gattinger/32/99690_2.png) [@Michael\_Gattinger](https://discuss.elastic.co/u/Michael_Gattinger)\
**Post date:** [October 23, 2022, 3:59am UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256/7 "2022-10-23T03:59:28Z")

</div>

I think @swallez maybe was wrong in this?

> [@Ways to build Json doc in ES8 Java API client](https://discuss.elastic.co/t/ways-to-build-json-doc-in-es8-java-api-client/314459):
>
> How to build Json document In Elasticsearch 8 API client , as In older Client APIs its possible to build using XContentBuilder like XContentBuilder builder = jsonBuilder() .startObject() .field("firstName", "jhon") .field("lastname", "doe") .field("message", "trying out Elasticsearch") .endObject()``` But now in ES8 Java API Client i do not see any way to build Json doc, for example if i want to insert a "Student" into "School" index , then possible ways are 1…

Thanks - Enomine

---

<div class="post-metadata">

**Author:** ![swallez](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/swallez/32/11972_2.png) [@swallez](https://discuss.elastic.co/u/swallez)\
**Post date:** [October 24, 2022, 8:13am UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256/8 "2022-10-24T08:13:25Z")

</div>

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:

```java
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.
    )
);

```

---

<div class="post-metadata">

**Author:** ![Michael\_Gattinger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/michael_gattinger/32/99690_2.png) [@Michael\_Gattinger](https://discuss.elastic.co/u/Michael_Gattinger)\
**Post date:** [October 27, 2022, 5:56am UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256/9 "2022-10-27T05:56:59Z")

</div>

Hey swallez,

thanks for that information.

So i wrote this to manage the same task:

```auto
pma = client.indices().putMapping(m -> m.index(rechnungen12)
			.properties("Rechnungsnummer", p -> p.integer(i -> i))
			.properties("Rechnungsdatum", p -> p.date(d -> d))
			.properties("Rechnungsbetrag", p -> p.float_(f -> f))
			.properties("Gläubiger", p -> p.text(t -> t))
			.properties("Schuldner", p -> p.text(t -> t)));
		System.out.println(pma.toString());

```

Thanks - Enomine

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [November 24, 2022, 5:57am UTC](https://discuss.elastic.co/t/how-to-use-xcontentbuilder-in-elasticsearch-8-0/317256/10 "2022-11-24T05:57:49Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
