IndexBiz.java
2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.cjs.cms.biz.elasticsearch;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.ResourceAlreadyExistsException;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.IndexNotFoundException;
import com.cjs.cms.util.elasticsearch.EsClient;
/**
* 创建索引
*
* @author tongyufu
*
*/
public class IndexBiz {
Logger log = LogManager.getLogger();
public static void main(String[] args) throws Exception {
IndexBiz index = new IndexBiz();
index.deleteIndex();
index.createIndex();
}
/**
* 创建索引
*/
public void createIndex() throws Exception {
TransportClient client = EsClient.getClient();
try {
Settings.Builder settings = Settings.builder();
settings.put("index.number_of_shards", "3");
settings.put("index.number_of_replicas", 2);
CreateIndexRequestBuilder build = client.admin().indices()
.prepareCreate(EsClient.INDEX);
File mappingFile = new File(
IndexBiz.class.getResource("/mapping/entrust.json").toURI());
String mapping = FileUtils.readFileToString(mappingFile);
log.info("创建索引:" + mapping);
build.addMapping(EsClient.TYPE, mapping);
CreateIndexResponse response = build.get();
log.info("reponse:" + response.isAcknowledged());
} catch (ResourceAlreadyExistsException e) {
log.error("索引已经存在:" + e.getMessage());
} finally {
client.close();
}
}
/**
* 删除索引
*/
public void deleteIndex() {
TransportClient client = EsClient.getClient();
log.info("================================");
try {
DeleteIndexResponse response = client.admin().indices().prepareDelete(EsClient.INDEX)
.get();
log.info("reponse:" + response.isAcknowledged());
log.info("================================");
} catch (IndexNotFoundException e) {
log.error("索引不存在:" + e.getMessage());
}
}
/**
* 更新索引设置
*/
public void updateIndexSettings() {
TransportClient client = EsClient.getClient();
log.info("================================");
client.admin().indices().prepareUpdateSettings(EsClient.INDEX)
.setSettings(Settings.builder().put("index.number_of_replicas", 2)).get();
client.close();
log.info("================================");
}
}