使用Java客户端设置Mappings
步骤
-
创建一个Settings对象,相当于是一个配置信息。主要配置集群的名称。
-
创建一个客户端Client对象。
-
使用client对象创建一个mapping信息(json数据,可以是字符串,也可以是XContextBuilder对象)。
-
使用client向es服务器发送mappings信息。
-
关闭client对象。
【案例】初始时index_hello的mappings为空,我们要对此索引的mappings进行设置。
(1)编写代码:
@Test
public void setMappings() throws Exception {
// 1.创建一个Settings对象
Settings settings = Settings.builder().put("cluster.name", "my-elasticsearch").build();
// 2.创建一个client对象
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301));
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302));
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
// 3.使用client对象创建一个mapping信息
// 创建一个mappings信息
XContentBuilder builder = XContentFactory.jsonBuilder();
builder
.startObject() // 左边的花括号
.startObject("article")
.startObject("properties")
.startObject("id")
.field("type", "long")
.field("store", true)
.endObject()
.startObject("title")
.field("type", "text")
.field("store", true)
.field("analyzer", "ik_smart")
.endObject()
.startObject("content")
.field("type", "text")
.field("store", true)
.field("analyzer", "ik_smart")
.endObject()
.endObject()
.endObject()
.endObject();
// 4.使用client向es服务器发送mapping信息
client.admin().indices()
.preparePutMapping("index_hello") // 设置要做映射的索引
.setType("article") // 设置要做映射的type
.setSource(builder) // mapping信息,可以是XContentBuilder对象,也可以是json格式的字符串
.get(); // 执行操作
// 5.关闭client对象
client.close();
}
(2)执行成功:
(3)观察数据,发现成功设置了mappings: