Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From Json String to XContentBuilder

I have a file in json format, is there a way to convert it to a XContentBuilder?

What I want to do is to read a file with some mapping and then convert it to XContentBuilder

Something like:

XContentBuilder builder = JsonXContent.contentBuilder().source(String json);
like image 524
tbo Avatar asked May 29 '15 14:05

tbo


1 Answers

Usually the API should accept a String or byte[] so you shouldn't need to convert. Maybe you want CreateIndexRequestBuilder#addMapping(String, String)?

If you really, really, really want an XContentBuilder you can make an XContentParser and copy the contents to a builder. As of Elasticsearch 5.2 this should do it:

    String message = "{\"test\":\"test\"}";
    XContentBuilder b = XContentFactory.jsonBuilder().prettyPrint();
    try (XContentParser p = XContentFactory.xContent(XContentType.JSON).createParser(NamedXContentRegistry.EMPTY, message)) {
        b.copyCurrentStructure(p);
    }
    System.err.println(b.string());

You could probably also do something with raw but I don't think that is worth it.

Pre 5.2 you don't need the NamedXContentRegistry.EMPTY, part.

like image 100
Nik Avatar answered Sep 23 '22 05:09

Nik