learn and grow up

spring-data-es抽象service集成简单增删查改之三

字数统计: 2.5k阅读时长: 14 min
2020/02/29 Share

写在前面

接二

代码

继续整理了后续的实现类,注释已经比较清楚了,不在此赘述

本次主要更新了基于ElasticsearchTemplate来进行操作,主要是实现了批量的操作

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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//EsTemplateBaseService.java
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.script.Script;

import java.util.List;

/**
* es java api操作接口类,基于es template实现
* @author yyt
* @param <T>
*/
public interface EsTemplateBaseService<T extends BaseDoc> extends EsDocService<T> {
/**
* 获取index name
* @return
*/
String getIndexName();

/**
* 获取type name
* @return
*/
String getTypeName();


List<T> bulkSaveOrUpdate(List<T> ts);

/**
* bulk save
* @param ts doc集合
* @param listener 自定义监听类
* @return
*/
List<T> bulkSaveOrUpdate(List<T> ts, BulkProcessor.Listener listener);
List<T> bulkDeleteByDocPrimaryKey(List<T> ts);

/**
* bulk delete
* @param ts doc集合
* @param listener 自定义监听类
* @return
*/
List<T> bulkDeleteByDocPrimaryKey(List<T> ts, BulkProcessor.Listener listener);

/**
* scroll 查询
* @param var1 查询条件
* @return
*/
List<T> scrollSearch(QueryBuilder var1);

/**
* scroll 查询
* @param var1 查询条件
* @param callBack 自定义的原始数据处理回调函数
* @return
*/
List<T> scrollSearch(QueryBuilder var1, ScrollDataCallBack callBack);

<E extends BaseDto> List<T> bulkDelete(List<E> ts);
/**
* 根据单个dto bulk delete
* @param e
* @param <E>
* @return
*/
<E extends BaseDto> List<T> bulkDelete(E e);

/**
* 根据dto更新,
* @param e dto
* @param script 更新内容
* @param <E>
* @return
*/
<E extends BaseDto> Long updateByQueryRequest(E e, Script script);

/**
* 根据boolQueryBuilder更新,
* @param boolQueryBuilder boolQueryBuilder
* @param script 更新内容
* @return
*/
Long updateByQueryRequest(QueryBuilder boolQueryBuilder, Script script);
/**
* 根据dto删除,逻辑删除
* @param e dto
* @param <E>
* @return
*/
<E extends BaseDto> Long deleteByQueryRequest(E e);

/**
* 根据boolQueryBuilders删除,逻辑删除
* @param boolQueryBuilder boolQueryBuilder
* @return
*/
Long deleteByQueryRequest(QueryBuilder boolQueryBuilder);

}


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.ClearScrollRequest;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.reindex.UpdateByQueryAction;
import org.elasticsearch.index.reindex.UpdateByQueryRequestBuilder;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder;
import org.springframework.data.mapping.MappingException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
* 用es template操作的抽象类,提供了大部分常用功能
* @author yyt
* @param <T>
*/
@Slf4j
@Component
public abstract class EsAbstractTemplateService<T extends BaseDoc> implements EsTemplateBaseService<T>, InitializingBean {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
private BulkProcessor bulkProcessor;
private Client client;

private String indexName;
private String typeName;

/**
* T的主键,注解为@Id的属性
*/
private ElasticsearchPersistentProperty idProperty;

private Class<T> Tcls;
private int batchSize = 1000;

/**
* 新增或者修改
* 新增的话会将id设置到doc的@id字段中
* @param t
* @return
*/
@Override
public T saveOrUpdate(T t){
//保存前逻辑处理
prepareSave(t);
String id=findIdValue(t);
if(StringUtils.isNotBlank(id)){
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.doc(JSON.toJSONString(t),XContentType.JSON);
UpdateQueryBuilder updateQuery = new UpdateQueryBuilder()
.withIndexName(getIndexName()).withType(getTypeName())
.withId(id)
.withUpdateRequest(updateRequest);
elasticsearchTemplate.update(updateQuery.build());
}else{
IndexQuery indexQuery= new IndexQueryBuilder().withIndexName(getIndexName()).withType(getTypeName())
.withObject(t)
.build();

elasticsearchTemplate.index(indexQuery);
}

return t;
}

/**
* 根据主键id删除。不用bulk,直接DeleteRequest
* @param id
* @return
*/
@Override
public T delete(String id){
if(StringUtils.isNotBlank(id)){
bulkDeleteByPrimaryKey(this.bulkProcessor,indexName, typeName, id);
}
return null;
}

/**
* 根据query scroll全量查询
* @param var1
* @return
*/
@Override
public Iterable<T> search(QueryBuilder var1){
return scrollSearch(var1);
}

/**
* 根据dto分页查询,由于之前业务限制,不能使用scroll分页。
* @param dto
* @param <E>
* @return
*/
@Override
public <E extends BaseDto> Map<String,Object> searchByPage(E dto){
QueryBuilder qbs=getQueryBuilderByDto(dto);
SearchQuery sq=buildCommonPageSearch(qbs,dto);
/*Page<T> rep= elasticsearchTemplate.startScroll(3000,sq,Tcls);*/
Page<T> rep = elasticsearchTemplate.queryForPage(sq,Tcls);
Map<String,Object> rem=new HashMap<>(2);

rem.put("total",rep.getTotalElements());
rem.put("data",rep.getContent());

/*elasticsearchTemplate.clearScroll(((ScrolledPage)rep).getScrollId());*/
return rem;
}

/**
* 根据dto全量scroll搜索
* @param t
* @param <E>
* @return
*/
@Override
public <E extends BaseDto> Iterable<T> search(E t){
QueryBuilder qbs=getQueryBuilderByDto(t);
return scrollSearch(qbs);
}

protected <E extends BaseDto> QueryBuilder getQueryBuilderByDto(E t){
QueryBuilder qbs=buildCommonQuery(t);

buildOwnQuery(qbs,t);
return qbs;
}

/**
* 根据业务主键判断是否已经有业务数据,有的话则填充es的id
* @param s
*/
protected abstract void prepareSave(T s);

/**
* 自己的分页查询,自己实现
* @param query
* @return
*/
/*protected abstract Page<T> ownPageSearch(SearchQuery query);*/

/**
* 默认初始化
*/
/*protected IiapAbstractTemplateDocService(){
init();
}*/
/**
* 由子类确定es-template并初始化
*/
/*@Autowired
protected IiapAbstractTemplateDocService(ElasticsearchTemplate elasticsearchTemplate){
this.elasticsearchTemplate=elasticsearchTemplate;
init();
}*/

@Override
public List<T> scrollSearch(QueryBuilder queryBuilder, ScrollDataCallBack callBack){
List<T> result=new ArrayList();
SearchRequestBuilder search = client.prepareSearch(indexName).setTypes(typeName);
search.addSort("_doc", SortOrder.ASC);
// 批量读取条数
search.setSize(batchSize);

search.setQuery(queryBuilder);
// 设置search context 快照维护20sec有效期
search.setScroll(TimeValue.timeValueSeconds(20));
// 获得首次查询结果
SearchResponse scrollResp = search.get();
Long totalHits=scrollResp.getHits().getTotalHits();


log.debug("scroll query count " + totalHits);
if(totalHits>0){
int count = 1;
do {
log.debug("scroll query times: " + count);
List<Map<String, Object>> subResult= readHits(scrollResp.getHits().getHits());
if(callBack!=null){
callBack.handleData(subResult);
}
addAllSub(result,subResult);
count++;
scrollResp = client.prepareSearchScroll(scrollResp.getScrollId())
.setScroll(TimeValue.timeValueSeconds(20))
.execute().actionGet();
} while (scrollResp.getHits().getHits().length != 0);
}

// 清除
ClearScrollRequest scrollRequest = new ClearScrollRequest();
scrollRequest.addScrollId(scrollResp.getScrollId());
client.clearScroll(scrollRequest);
return result;
}


@Override
public List<T> scrollSearch(QueryBuilder queryBuilder){
return scrollSearch(queryBuilder,null);
}

/**
* 将es返回的默认结构解析并放入result
* 个性化的doc需要子类重写
* @param result
* @param subResult
*/
protected void addAllSub(List<T> result, List<Map<String, Object>> subResult) {
if(CollectionUtils.isEmpty(subResult)){
return;
}
subResult.forEach(e->{
T t=JSONObject.parseObject(JSONObject.toJSONString(e),Tcls);
putIdValue(t,(String) e.get("_idValue"));
result.add(t);
});
}


private List<Map<String, Object>> readHits(SearchHit[] searchHits){
List<Map<String, Object>> list = new ArrayList<>();
for (SearchHit hit: searchHits){
Map<String, Object> map = hit.getSource();
map.put("_idValue", hit.getId());
list.add(map);
}
return list;
}

private BulkProcessor buildBulkProcessor(BulkProcessor.Listener listener){
return BulkProcessor.builder(this.client, listener)
// 每n个action flush一次
.setBulkActions(getBatchSize())
// bulk数据每达到nMB flush一次
.setBulkSize(new ByteSizeValue(4, ByteSizeUnit.MB))
.setConcurrentRequests(0)
.setFlushInterval(TimeValue.timeValueSeconds(3))
.build();
}

/**
* bulk新增或者修改
* @param ts
* @return
*/
@Override
public List<T> bulkSaveOrUpdate(List<T> ts){
if(CollectionUtils.isNotEmpty(ts)){
ts.forEach(e->{
prepareSave(e);
bulkSaveOrUpdate(this.bulkProcessor,indexName, typeName, e);
});
}
return ts;
}

/**
* bulk新增或者修改
* @param ts
* @param listener 自定义的监听器
* @return
*/
@Override
public List<T> bulkSaveOrUpdate(List<T> ts,BulkProcessor.Listener listener){
BulkProcessor own=buildBulkProcessor(listener);
if(CollectionUtils.isNotEmpty(ts)){
ts.forEach(e->{
bulkSaveOrUpdate(own,indexName, typeName, e);
});
}
return ts;
}
/**
* bulk删除
* @param ts
* @param listener 自定义的监听器
* @return
*/
@Override
public List<T> bulkDeleteByDocPrimaryKey(List<T> ts,BulkProcessor.Listener listener){
BulkProcessor own=buildBulkProcessor(listener);
if(CollectionUtils.isNotEmpty(ts)){
ts.forEach(e->{
bulkDeleteByPrimaryKey(own,indexName, typeName, findIdValue(e));
});
}
return ts;
}

/**
* 按照es的主键id删除
* @param ts
* @return
*/
@Override
public List<T> bulkDeleteByDocPrimaryKey(List<T> ts){
if(CollectionUtils.isNotEmpty(ts)){
ts.forEach(e->{
bulkDeleteByPrimaryKey(this.bulkProcessor,indexName, typeName, findIdValue(e));
});
}
return ts;
}

/**
* 按照doc里的属性来删除
* @param ts
* @return
*/
@Override
public <E extends BaseDto> List<T> bulkDelete(List<E> ts){
List<T> rs=new ArrayList<>();
if(CollectionUtils.isNotEmpty(ts)){
ts.forEach(e->{
Iterable<T> es= search(e);
if(!IterableUtils.isEmpty(es)){
es.forEach(t->{
rs.add(t);
bulkDeleteByPrimaryKey(this.bulkProcessor,indexName, typeName, findIdValue(t));
});
}
});
}
return rs;
}

/**
* 根据单个dto bulk delete
* @param e
* @param <E>
* @return
*/
@Override
public <E extends BaseDto> List<T> bulkDelete(E e){
List<E> list=new ArrayList<>();
list.add(e);
return bulkDelete(list);
}

/**
* bulk 新增或者修改
* @param ownbulkProcessor bulk processor
* @param indexName
* @param typeName
* @param obj
*/
private void bulkSaveOrUpdate(BulkProcessor ownbulkProcessor,String indexName, String typeName, T obj){
String id=findIdValue(obj);
if(StringUtils.isNotBlank(id)){
UpdateRequest indexRequest = new UpdateRequest()
.index(indexName)
.type(typeName).id(id)
.doc(JSON.toJSONString(obj), XContentType.JSON);
ownbulkProcessor.add(indexRequest);
}else{
IndexRequest indexRequest = new IndexRequest()
.index(indexName)
.type(typeName)
.source(JSON.toJSONString(obj), XContentType.JSON);
ownbulkProcessor.add(indexRequest);
}
}

/**
* 根据主键bulk删除
* @param ownbulkProcessor
* @param indexName
* @param typeName
* @param id es的主键id
*/
private void bulkDeleteByPrimaryKey(BulkProcessor ownbulkProcessor,String indexName, String typeName, String id){
if(StringUtils.isNotBlank(id)){
/*DeleteRequest indexRequest = new DeleteRequest()
.index(indexName)
.type(typeName).id(id);
ownbulkProcessor.add(indexRequest);*/
UpdateRequest updateRequest= null;
try {
updateRequest = new UpdateRequest().index(indexName).type(typeName).id(id).doc(jsonBuilder().startObject()
// 对没有的字段添加, 对已有的字段替换
.field("deleted", BaseConstant.FILED_DELETED).endObject());
ownbulkProcessor.add(updateRequest);
} catch (IOException e) {
log.error("bulkDeleteByPrimaryKey jsonBuilder error:{}-{}-{}",indexName,typeName,id);
throw new CustomBusinessException(ErrorCodeUtils.CommonErrorCode.ERROR_SERVER_INTERNAL,"bulkDeleteByPrimaryKey jsonBuilder error");
}
}
}

@Override
public <E extends BaseDto> Long updateByQueryRequest(E e, Script script){
QueryBuilder qbs=getQueryBuilderByDto(e);
return updateByQueryRequest(qbs,script);
}

@Override
public Long updateByQueryRequest(QueryBuilder queryBuilder, Script script){
Long count=doCount(queryBuilder);
if(count==0){
return 0L;
}

UpdateByQueryRequestBuilder updateByQuery = UpdateByQueryAction.INSTANCE.newRequestBuilder(client)
//为了防止版本冲突导致updateByQuery中止,设置终止冲突为(false)
.abortOnVersionConflict(false);
updateByQuery.source(getIndexName())
.filter(queryBuilder)
.size(count.intValue())
.script(script);
long updated = updateByQuery.get().getUpdated();
log.debug("update success:{}-{}",queryBuilder,updated);
return updated;
}

private Long doCount(QueryBuilder queryBuilder){
SearchRequestBuilder countRequestBuilder = this.client.prepareSearch(getIndexName());
countRequestBuilder.setSize(0);
countRequestBuilder.setQuery(queryBuilder);
return (countRequestBuilder.execute().actionGet()).getHits().getTotalHits();
}

@Override
public <E extends BaseDto> Long deleteByQueryRequest(E e){
QueryBuilder qbs=getQueryBuilderByDto(e);
Script script= new Script("ctx._source.deleted = '"+BaseConstant.FILED_DELETED+"'" +
";ctx._source.updatedTime='"+System.currentTimeMillis()+"'");
return updateByQueryRequest(qbs,script);
}

@Override
public Long deleteByQueryRequest(QueryBuilder queryBuilder){
Script script= new Script("ctx._source.deleted = '"+BaseConstant.FILED_DELETED+"'" +
";ctx._source.updatedTime='"+System.currentTimeMillis()+"'");
return updateByQueryRequest(queryBuilder,script);
}

protected void setIndexName(String writeIndexName){
this.indexName=writeIndexName;
}

protected void setTypeName(String typeName){
this.typeName=typeName;
}

@Override
public String getIndexName(){
return this.indexName;
}
@Override
public String getTypeName(){
return this.typeName;
}

@Override
public void afterPropertiesSet() throws Exception{
init();
}

/**
* 确定bulkProcess index、 client,idProperty
*/
protected void init(){
this.client=this.elasticsearchTemplate.getClient();
this.bulkProcessor = buildBulkProcessor(new BulkProcessor.Listener(){
@Override
public void beforeBulk(long l, BulkRequest bulkRequest) {
}

@Override
public void afterBulk(long l, BulkRequest bulkRequest, Throwable throwable) {
log.error(" bulk insert_error : {}", throwable);
}

@Override
public void afterBulk(long l, BulkRequest bulkRequest, BulkResponse bulkResponse) {
log.debug(" bulk insert success size: {}",bulkRequest.numberOfActions());
}
});

//根据泛型获取默认的index和type
this.Tcls=(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
Assert.isTrue(Tcls.isAnnotationPresent(Document.class), "Unable to identify index name. " + Tcls.getSimpleName() + " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")");
Document document = this.Tcls.getAnnotation(Document.class);
setIndexName(document.indexName());
setTypeName(document.type());
this.idProperty= (ElasticsearchPersistentProperty)elasticsearchTemplate.getPersistentEntityFor(Tcls).getIdProperty();
if(idProperty == null || !idProperty.getType().isAssignableFrom(String.class)){
throw new MappingException(String.format("Couldn't find idProperty for type %s!", Tcls.getSimpleName()));
}
}

/**
* 获取T的主键的值
* @return
*/
protected String findIdValue(T t){
return (String) elasticsearchTemplate.getPersistentEntityFor(Tcls).getPropertyAccessor(t).getProperty(idProperty);
}

/**
* 设置主键的值
* @param t
* @param id
*/
protected void putIdValue(T t,String id){
elasticsearchTemplate.getPersistentEntityFor(Tcls).getPropertyAccessor(t).setProperty(idProperty,id);
}

/**
* 获取批处理批次数
* @return
*/
protected int getBatchSize(){
return this.batchSize;
}
}
CATALOG
  1. 1. 写在前面
  2. 2. 代码