java创建mapping_ElasticSearch使用Java客户端创建索引index和映射mapping

1.创建工程,导入pom.xml坐标

org.elasticsearch

elasticsearch

5.6.8

org.elasticsearch.client

transport

5.6.8

org.apache.logging.log4j

log4j‐to‐slf4j

2.9.1

org.slf4j

slf4j‐api

1.7.24

org.slf4j

slf4j‐simple

1.7.21

log4j

log4j

1.2.12

junit

junit

4.12

2.创建索引index

@Test

//创建索引

publicvoidtest1() throwsException{

// 创建Client连接对象

Settings settings=Settings.builder().put("cluster.name", "my‐elasticsearch").build();

TransportClient client=new PreBuiltTransportClient(settings) .addTransportAddress(newInetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9300));

//创建名称为blog2的索引

client.admin().indices().prepareCreate("blog2").get();

//释放资源

client.close();

}

这样就可以看到新的索引:

java创建mapping_ElasticSearch使用Java客户端创建索引index和映射mapping_第1张图片

但是当前映射没有信息:

java创建mapping_ElasticSearch使用Java客户端创建索引index和映射mapping_第2张图片

3.创建映射mapping

@Test

//创建映射

publicvoidtest3() throwsException{

// 创建Client连接对象

Settings settings=Settings.builder().put("cluster.name", "my‐elasticsearch").build();

TransportClient client=new PreBuiltTransportClient(settings) .addTransportAddress(newInetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9300));

// 添加映射

/**

* 格式:

* "mappings" : {

"article" : {

"dynamic" : "false",

"properties" : {

"id" : { "type" : "string" },

"content" : { "type" : "string" },

"author" : { "type" : "string" }

}

}

}*/

XContentBuilder builder=XContentFactory.jsonBuilder()

.startObject()

.startObject("article")

.startObject("properties")

.startObject("id")

.field("type", "integer"

.field("store", "yes")

.endObject()

.startObject("title")

.field("type", "string")

.field("store", "yes")

.field("analyzer", "ik_smart")

.endObject()

.startObject("content")

.field("type", "string")

.field("store", "yes")

.field("analyzer", "ik_smart")

.endObject()

.endObject()

.endObject()

.endObject();

// 创建映射

PutMappingRequestmapping=Requests.putMappingRequest("blog2")

.type("article").source(builder);

client.admin().indices().putMapping(mapping).get();

//释放资源

client.close();

}

这样就能看到对应的映射信息了:

java创建mapping_ElasticSearch使用Java客户端创建索引index和映射mapping_第3张图片

你可能感兴趣的:(java创建mapping)