PoolService.java
13.1 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package com.viontech.match.service;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.ElasticsearchException;
import co.elastic.clients.elasticsearch._types.mapping.AllField;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.CountRequest;
import co.elastic.clients.elasticsearch.core.CountResponse;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.alibaba.fastjson.JSONObject;
//import com.fasterxml.jackson.databind.ObjectMapper;
import com.viontech.keliu.model.Person;
import com.viontech.match.config.Constant;
import com.viontech.match.entity.PoolInfo;
import com.viontech.match.entity.vo.RequestVo;
import com.viontech.match.entity.vo.ResponseVo;
import com.viontech.match.runner.ILM;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* .
*
* @author 谢明辉
* @version 0.0.1
*/
@Service
@Slf4j
public class PoolService {
@Resource
private PersonService personService;
@Resource
private ElasticsearchClient client;
// @Resource
// private ObjectMapper objectMapper;
@Value("${vion.index.number_of_shards:1}")
private Integer shards;
@Value("${vion.index.number_of_replicas:0}")
private Integer replicas;
@Value("${vion.index.translog.durability:async}")
private String translogDurability;
// @Value("${vion.index.refresh_interval}")
// private String refreshInterval;
@Value("${vion.index.translog.sync_interval}")
private String translogSyncInterval;
@Value("${vion.index.merge.scheduler.max_thread_count}")
private Integer mergeThreadCount;
/**
* 添加特征池
*
* @param requestVo rid, poolId, personPool
*
* @return ResponseVo
* @throws Exception --
*/
public ResponseVo createPool(RequestVo requestVo) throws Exception {
return createPool(requestVo, true);
}
public ResponseVo createPool(RequestVo requestVo, boolean addPerson) throws Exception {
String rid = requestVo.getRid();
String poolId = requestVo.getPoolId();
// log.info("特征池创建操作开始:[{}},IML:{}", poolId, requestVo.isUseILMPolicy());
try {
IndexSettings.Builder settings = new IndexSettings.Builder()
.numberOfShards(String.valueOf(shards))
.numberOfReplicas(String.valueOf(replicas));
if (StringUtils.isNotEmpty(translogDurability)) {
settings.translog(t -> t.durability(TranslogDurability.Async));
if (StringUtils.isNotEmpty(translogSyncInterval)) {
settings.translog(t -> t.syncInterval(i -> i.time(translogSyncInterval)));
}
}
if (mergeThreadCount != null) {
settings.merge(m -> m.scheduler(s -> s.maxThreadCount(mergeThreadCount)));
}
if (requestVo.isUseILMPolicy()) {
settings.lifecycle(l -> l.name(ILM.LIFECYCLE_NAME));
}
TypeMapping.Builder builder = getCreateIndexContentBuilder();
CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder().index(poolId).mappings(builder.build()).settings(settings.build()).build();
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest);
if (addPerson) {
List<Person> personPool = requestVo.getPersonPool();
if (CollectionUtils.isNotEmpty(personPool)) {
BulkResponse bulkItemResponses = personService.addPerson(poolId, personPool);
if (bulkItemResponses != null) {
log.info(bulkItemResponses.toString());
}
}
}
log.info("特征池创建完成:[{}],ILM:{}", poolId, requestVo.isUseILMPolicy());
return ResponseVo.success(rid);
} catch (ElasticsearchException e) {
if (e.status() == 400 && e.getMessage().contains(Constant.STR_POOL_ID_ALREADY_EXISTS)) {
return ResponseVo.error(rid, 20, "already exit poolId");
} else {
throw e;
}
}
}
/**
* 删除特征池
*
* @param requestVo rid,flushPool,poolId,personIds,
*
* @return ResponseVo
* @throws Exception --
*/
public ResponseVo deletePool(RequestVo requestVo) throws Exception {
String rid = requestVo.getRid();
Integer flushPool = requestVo.getFlushPool();
String poolId = requestVo.getPoolId();
// log.info("特征池删除操作开始:[{}],FlushPool:[{}]", poolId, flushPool);
try {
if (0 == flushPool) {
List<HashMap<String, String>> personIds = requestVo.getPersonIds();
for (HashMap<String, String> item : personIds) {
String personId = item.get("personId");
if (personId != null) {
personService.deletePerson(poolId, personId);
}
}
} else if (flushPool == 1) {
//删除索引
DeleteIndexResponse delete = client.indices().delete(new DeleteIndexRequest.Builder().index(poolId).build());
}
log.info("特征池删除完成:[{}],FlushPool:[{}]", poolId, flushPool);
return ResponseVo.success(rid);
} catch (ElasticsearchException e) {
if (e.status() == 404) {
return ResponseVo.poolIdNotExists(rid);
} else {
return ResponseVo.error(rid, e.getMessage());
}
}
}
public ResponseVo deletePoolData(RequestVo requestVo) throws Exception {
String rid = requestVo.getRid();
Integer flushPool = requestVo.getFlushPool();
String poolId = requestVo.getPoolId();
Long mallId = requestVo.getMallId();
log.info("特征池删除mallId:{}数据操作开始:[{}]", mallId,poolId);
try {
personService.deletePersonByMallId(poolId, mallId);
log.info("特征池删除mallId:{}操作完成:[{}]", mallId, poolId);
return ResponseVo.success(rid);
} catch (ElasticsearchException e) {
if (e.status() == 404) {
return ResponseVo.poolIdNotExists(rid);
} else {
return ResponseVo.error(rid, e.getMessage());
}
}
}
public ResponseVo deleteStaffPoolData(RequestVo requestVo) throws Exception {
String rid = requestVo.getRid();
Integer flushPool = requestVo.getFlushPool();
String poolId = requestVo.getPoolId();
List<String> fidList = requestVo.getFidList();
log.info("店员特征池删除数据操作开始:[{}]",poolId);
try {
personService.deletePersonByFid(poolId, fidList);
log.info("店员特征池删除操作完成:[{}]",poolId);
return ResponseVo.success(rid);
} catch (ElasticsearchException e) {
if (e.status() == 404) {
return ResponseVo.poolIdNotExists(rid);
} else {
return ResponseVo.error(rid, e.getMessage());
}
}
}
/**
* 修改特征池(添加人员)
*
* @param requestVo rid,poolId,personPool,updateType
*
* @return ResponseVo
* @throws Exception --
*/
public ResponseVo modifyPool(RequestVo requestVo) throws Exception {
String rid = requestVo.getRid();
String poolId = requestVo.getPoolId();
List<Person> personPool = requestVo.getPersonPool();
Integer updateType = requestVo.getUpdateType();
// log.info("特征池修改操作开始:[{}],updateType:[{}]", poolId, updateType);
co.elastic.clients.elasticsearch.indices.ExistsRequest poolIdExists = new ExistsRequest.Builder().index(poolId).build();
BooleanResponse poolIdExistsResponse = client.indices().exists(poolIdExists);
if (!poolIdExistsResponse.value()) {
return ResponseVo.poolIdNotExists(rid);
}
try {
BulkResponse bulkItemResponses = personService.addPerson(poolId, personPool);
if (bulkItemResponses != null && bulkItemResponses.errors()) {
log.info(bulkItemResponses.items().toString());
return ResponseVo.error(rid, bulkItemResponses.items().toString());
}
log.info("特征池修改:[{}],updateType:[{}]", poolId, updateType);
return ResponseVo.success(rid, "success");
} catch (ElasticsearchException e) {
log.error("modifyPool", e);
return ResponseVo.error(rid, e.getMessage());
}
}
/**
* 查询特征池信息
*
* @param requestVo rid,listAll,poolId
*
* @return ResponseVo
* @throws Exception --
*/
public ResponseVo queryPool(RequestVo requestVo) throws Exception {
String rid = requestVo.getRid();
Integer listAll = requestVo.getListAll();
String poolId = requestVo.getPoolId();
try {
List<PoolInfo> poolInfos;
// log.info("查询特征池操作开始:[{}],rid:[{}]", poolId, rid);
if (listAll != 0) {
poolInfos = queryPoolInfo(poolId);
} else {
if (!existPool(poolId)) {
return ResponseVo.poolIdNotExists(rid);
}
poolInfos = queryPoolInfo(poolId);
}
ResponseVo success = ResponseVo.success(rid, "success");
success.setPoolIds(poolInfos);
log.info("查询特征池完成:[{}],rid:[{}]", poolId, rid);
return success;
} catch (ElasticsearchException e) {
log.error("queryPool", e);
return ResponseVo.error(rid, e.getMessage());
}
}
public void refreshPool(String... poolIds) throws IOException {
RefreshRequest refreshRequest = new RefreshRequest.Builder().index(Arrays.asList(poolIds)).build();
RefreshResponse refresh = client.indices().refresh(refreshRequest);
// log.info("刷新索引:{},成功:{},失败:{}", poolIds, refresh.shards().successful(), refresh.shards().failed());
}
public TypeMapping.Builder getCreateIndexContentBuilder() throws IOException {
Map<String, Property> properties = new HashMap<>();
properties.put("direction", new Property.Builder().keyword(k -> k.index(true)).build());
properties.put("fid", new Property.Builder().text(t -> t.index(true)).build());
properties.put("gateId", new Property.Builder().long_(t -> t.index(true)).build());
properties.put("personId", new Property.Builder().keyword(k -> k.index(true)).build());
properties.put("body", new Property.Builder().denseVector(d -> d.dims(Constant.BODY_FEATURE_DIMS_2048).similarity("cosine")).build());
properties.put("data", new Property.Builder().denseVector(d -> d.dims(Constant.FACE_FEATURE_DIMS).similarity("cosine")).build());
properties.put("body_type", new Property.Builder().integer(i -> i.index(false).docValues(false)).build());
properties.put("channelSerialNum", new Property.Builder().keyword(k -> k.index(true)).build());
properties.put("age", new Property.Builder().integer(i -> i.index(false).docValues(false)).build());
properties.put("gender", new Property.Builder().keyword(k -> k.index(false).docValues(false)).build());
properties.put("counttime", new Property.Builder().date(d -> d.format("yyyy-MM-dd HH:mm:ss")).build());
properties.put("unid", new Property.Builder().keyword(k -> k.index(true)).build());
properties.put("mallId", new Property.Builder().keyword(k -> k.index(true)).build());
TypeMapping.Builder builder = new TypeMapping.Builder().properties(properties);
return builder;
}
public boolean existPool(String poolId) throws IOException {
BooleanResponse exists = client.indices().exists(new ExistsRequest.Builder().index(poolId).build());
return exists.value();
}
public List<PoolInfo> queryPoolInfo(String poolId) throws IOException {
CountResponse response = client.count(new CountRequest.Builder().index(poolId).build());
LinkedList<PoolInfo> poolInfos = new LinkedList<>();
PoolInfo poolInfo = new PoolInfo();
poolInfo.setPersonCount( response.count());
poolInfo.setPoolId(poolId);
poolInfos.add(poolInfo);
return poolInfos;
}
}