Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add type mapping with JSON schema and ElasticSearch Java API

Is it possible to add a type mapping to an ElasticSearch Index with the Java API using a JSON schema?

I know that ElasticSearch uses the first document to create a mapping and therefor i could enhance my first document with json schema. But i want to create the types before indexing an document.

like image 371
Cengiz Avatar asked Sep 06 '14 08:09

Cengiz


People also ask

What is mapping type in Elasticsearch?

Elasticsearch supports two types of mappings: “Static Mapping” and “Dynamic Mapping.” We use Static Mapping to define the index and data types. However, we still need ongoing flexibility so that documents can store extra attributes.

Can we update mapping in Elasticsearch?

If the Elasticsearch security features are enabled, you must have the manage index privilege for the target data stream, index, or alias. [7.9] If the request targets an index or index alias, you can also update its mapping with the create , create_doc , index , or write index privilege.


1 Answers

You could do something like:

String mapping = XContentFactory.jsonBuilder().startObject().startObject(typeName).startObject("properties")
                    .startObject("location").field("type", "geo_point").endObject()
                    .startObject("language").field("type", "string").field("index", "not_analyzed").endObject()
                    .startObject("user").startObject("properties").startObject("screen_name").field("type", "string").field("index", "not_analyzed").endObject().endObject().endObject()
                    .startObject("mention").startObject("properties").startObject("screen_name").field("type", "string").field("index", "not_analyzed").endObject().endObject().endObject()
                    .startObject("in_reply").startObject("properties").startObject("user_screen_name").field("type", "string").field("index", "not_analyzed").endObject().endObject().endObject()
                    .startObject("retweet").startObject("properties").startObject("user_screen_name").field("type", "string").field("index", "not_analyzed").endObject().endObject().endObject()
                    .endObject().endObject().endObject().string();
client.admin().indices().preparePutMapping(indexName).setType(typeName).setSource(mapping).execute().actionGet();

Or if you have your mapping as a String

String json = "{}";
PutMappingResponse response = client.admin().indices()
                    .preparePutMapping(index)
                    .setType(type)
                    .setSource(json)
                    .execute().actionGet();     
like image 57
dadoonet Avatar answered Oct 23 '22 02:10

dadoonet