Mapping is to define the field names and Data Types of indexes in the index database. It is similar to defining the field names and data types when creating tables in relational databases. However, the mapping of ES is much more flexible than that of databases, it can dynamically add fields. Generally, you do not need to specify mapping because elasticsearch automatically defines its type based on the data format. If you need to add special attributes to some fields (for example: you must manually add ing. There are two ways to add mapping. One is defined in the configuration file, the other is to manually submit mapping during running, and the other is to choose one.
First, we will introduce how to define mapping in the configuration file. You can set the [mapping name]. put the JSON file in the config/mappings/[index name] Directory, which must be created by yourself. A Mapping corresponds to an index. You can also define a default mapping, put your own defined default-mapping.json under the config directory. The JSON format is as follows:
{ "mappings":{ "properties":{ "title":{ "type":"string", "store":"yes" }, "description":{ "type":"string", "index":"not_analyzed" }, "price":{ "type":"double" }, "onSale":{ "type":"boolean" }, "type":{ "type":"integer" }, "createDate":{ "type":"date" } } }}
Next we will introduce how to add mapping through requests. Below is a JSON format request for mapping to add the productindex index library. Here, productindex is the index type, and properties contains the fields in the index. type is the data type, store is storage, and "Index": "not_analyzed" indicates that this field is not segmented.
{ "productIndex":{ "properties":{ "title":{ "type":"string", "store":"yes" }, "description":{ "type":"string", "index":"not_analyzed" }, "price":{ "type":"double" }, "onSale":{ "type":"boolean" }, "type":{ "type":"integer" }, "createDate":{ "type":"date" } } }}
The code for calling a Java API is as follows:
Create an empty index database first
client.admin().indices().prepareCreate("productIndex").execute().actionGet();
Put Mapping
XContentBuilder mapping = jsonBuilder() .startObject() .startObject("productIndex") .startObject("properties") .startObject("title").field("type", "string").field("store", "yes").endObject() .startObject("description").field("type", "string").field("index", "not_analyzed").endObject() .startObject("price").field("type", "double").endObject() .startObject("onSale").field("type", "boolean").endObject() .startObject("type").field("type", "integer").endObject() .startObject("createDate").field("type", "date").endObject() .endObject() .endObject() .endObject(); PutMappingRequest mappingRequest = Requests.putMappingRequest("productIndex").type("productIndex").source(mapping); client.admin().indices().putMapping(mappingRequest).actionGet();