EsTool.java
9.25 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package com.lhcredit.common.utils.elasticSearchUtils;
import com.alibaba.fastjson.JSONObject;
import com.lhcredit.common.utils.elasticSearchUtils.config.EsConfig;
import com.lhcredit.project.system.dict.domain.DictData;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
@Component
public class EsTool {
/**ik分词字段 */
private String[] ikField;
public EsTool ikField(String... FieldName){
this.ikField=FieldName;
return this;
}
/**开启fieldData的字段 */
private String[] fieldData;
public EsTool fieldData(String... fieldData){
this.fieldData=fieldData;
return this;
}
private Long scrollTime=30000L ;//设置scroll保存时间 分钟单位
private Integer number_of_shards=1;//设置分片
private Integer number_of_replicas=1;//设置副本
@Autowired
private RestHighLevelClient client;
@Autowired
private EsConfig esConfig;
public static Logger log= LoggerFactory.getLogger(EsTool.class);
/**根据实体类创建索引 index和type相同 */
public Boolean createIdx(Class cs,String idx,String typeName) throws IOException {
//获取字段
Field[] fields = cs.getDeclaredFields();
//验证索引
// if(isExistsIndex(cs.getSimpleName().toLowerCase())){
// return false;
// }
log.info("index={}", cs.getSimpleName().toLowerCase());
//索引和type同名,全部小写
// CreateIndexRequest request = new CreateIndexRequest("lhtlzsh");
CreateIndexRequest request = new CreateIndexRequest(idx);
XContentBuilder builder = JsonXContent.contentBuilder();
builder.startObject()
.startObject("mappings")
// .startObject("lhtlzsh")
.startObject(typeName)
.startObject("properties");
for(Field field : fields){
Class<?> type = field.getType();
//这里只对String类型的字段添加ik中文分词处理
if(type.getSimpleName().equals("String")) {
if (Arrays.asList(ikField).contains(field.getName())) {
//分词
builder.startObject(field.getName())
.field("type", "text")
.field("index", true)
.field("analyzer", "ik_max_word")
// .field("analyzer","standard")
.endObject();
}else {
//不分词
builder.startObject(field.getName())
.field("type", "text")
.field("index", true)
.endObject();
}
}
//对数字处理
if(type.getSimpleName().equals("Integer")||type.getSimpleName().equals("int")){
builder.startObject(field.getName())
.field("type","integer")
.field("index",true)
.endObject();
}
if(type.getSimpleName().equals("Long")||type.getSimpleName().equals("long")){
builder.startObject(field.getName())
.field("type","long")
.field("index",true)
.endObject();
}
if(type.getSimpleName().equals("Float")||type.getSimpleName().equals("float")){
builder.startObject(field.getName())
.field("type","float")
.field("index",true)
.endObject();
}
if(type.getSimpleName().equals("Double")||type.getSimpleName().equals("double")||type.getSimpleName().equals("BigDecimal")){
builder.startObject(field.getName())
.field("type","double")
.field("index",true)
.endObject();
}
//日期
if(type.getSimpleName().equals("Date")){
builder.startObject(field.getName())
.field("type","date")
.field("index",true)
.endObject();
}
//boolean
if(type.getSimpleName().equals("Boolean")||type.getSimpleName().equals("boolean")){
builder.startObject(field.getName())
.field("type","boolean")
.field("index",true)
.endObject();
}
}
builder.endObject().endObject().endObject();
builder.startObject("settings")
//分片数
.field("number_of_shards",number_of_shards)
//副本数,1台机器设为0
.field("number_of_replicas",number_of_replicas)
.endObject()
.endObject();
request.source(builder);
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
log.info(JSONObject.toJSONString(response));
return response.isAcknowledged();
}
/** 删除索引 */
public boolean deleteIndex(String index){
if(!isExistsIndex(index)){
return false;
};
DeleteIndexRequest request=new DeleteIndexRequest(index);
try {
AcknowledgedResponse deleteIndexResponse = client.indices().delete(request,RequestOptions.DEFAULT);
return deleteIndexResponse.isAcknowledged();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**验证索引是否存在 */
public boolean isExistsIndex(String indexName){
try{
GetIndexRequest request = new GetIndexRequest();
request.indices(indexName);
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
return exists;
}catch (Exception e){
e.printStackTrace();
}
return false;
}
//设置fieldData
public void setFieldData(String idx,String... field){
for(int i=0;i<field.length;i++){
String url="http://"+esConfig.getHost()+":"+esConfig.getPort()+"/"+idx+"/"+idx+"/_mapping";
String data="{\"properties\":{\""+field[i]+"\":{\"type\": \"text\",\"fielddata\": true}}}";
String request=doPut(url,data);
System.out.println("开启"+field[i]+":"+request);
}
}
//put请求
public String doPut(String url, String jsonStr) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
httpPut.setConfig(requestConfig);
httpPut.setHeader("Content-type", "application/json");
httpPut.setHeader("DataEncoding", "UTF-8");
// httpPut.setHeader("token", token);
CloseableHttpResponse httpResponse = null;
try {
httpPut.setEntity(new StringEntity(jsonStr));
httpResponse = httpClient.execute(httpPut);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
return result;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}