Merge pull request #1523 from rewerma/master

es adapter新增upsert属性
This commit is contained in:
agapple
2019-02-25 14:50:58 +08:00
committed by GitHub
11 changed files with 878 additions and 976 deletions

View File

@@ -67,8 +67,8 @@ public class YmlConfigBinder {
} }
/** /**
* 将当前内容指定前缀部分绑定到指定对象并用环境变量中的属性替换占位符, 例: 当前内容有属性 zkServers: * 将当前内容指定前缀部分绑定到指定对象并用环境变量中的属性替换占位符, 例: 当前内容有属性 zkServers: ${zookeeper.servers}
* ${zookeeper.servers} 在envProperties中有属性 zookeeper.servers: * 在envProperties中有属性 zookeeper.servers:
* 192.168.0.1:2181,192.168.0.1:2181,192.168.0.1:2181 则当前内容 zkServers 会被替换为 * 192.168.0.1:2181,192.168.0.1:2181,192.168.0.1:2181 则当前内容 zkServers 会被替换为
* zkServers: 192.168.0.1:2181,192.168.0.1:2181,192.168.0.1:2181 注: 假设绑定的类中 * zkServers: 192.168.0.1:2181,192.168.0.1:2181,192.168.0.1:2181 注: 假设绑定的类中
* zkServers 属性是 List<String> 对象, 则会自动映射成List * zkServers 属性是 List<String> 对象, 则会自动映射成List
@@ -109,8 +109,7 @@ public class YmlConfigBinder {
properties = baseProperties; properties = baseProperties;
} }
for (Object o : ((Map<?, ?>) propertySource.getSource()).entrySet()) { for (Map.Entry<?, ?> entry : ((Map<?, ?>) propertySource.getSource()).entrySet()) {
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
String key = (String) entry.getKey(); String key = (String) entry.getKey();
Object value = entry.getValue(); Object value = entry.getValue();
@@ -122,9 +121,9 @@ public class YmlConfigBinder {
} }
} }
if (value != null && value.toString().contains("${")) { if (value instanceof String && ((String) value).contains("${") && ((String) value).contains("}")) {
PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}"); PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}");
value = propertyPlaceholderHelper.replacePlaceholders(value.toString(), properties); value = propertyPlaceholderHelper.replacePlaceholders((String) value, properties);
} }
propertiesRes.put(key, value); propertiesRes.put(key, value);

View File

@@ -144,11 +144,14 @@ public class ESAdapter implements OuterAdapter {
return; return;
} }
for (Dml dml : dmls) { for (Dml dml : dmls) {
sync(dml); if (!dml.getIsDdl()) {
sync(dml);
}
} }
esSyncService.commit(); // 批次统一提交
} }
public void sync(Dml dml) { private void sync(Dml dml) {
String database = dml.getDatabase(); String database = dml.getDatabase();
String table = dml.getTable(); String table = dml.getTable();
Map<String, ESSyncConfig> configMap; Map<String, ESSyncConfig> configMap;
@@ -174,7 +177,7 @@ public class ESAdapter implements OuterAdapter {
DataSource dataSource = DatasourceConfig.DATA_SOURCES.get(config.getDataSourceKey()); DataSource dataSource = DatasourceConfig.DATA_SOURCES.get(config.getDataSourceKey());
ESEtlService esEtlService = new ESEtlService(transportClient, config); ESEtlService esEtlService = new ESEtlService(transportClient, config);
if (dataSource != null) { if (dataSource != null) {
return esEtlService.importData(params, false); return esEtlService.importData(params);
} else { } else {
etlResult.setSucceeded(false); etlResult.setSucceeded(false);
etlResult.setErrorMessage("DataSource not found"); etlResult.setErrorMessage("DataSource not found");
@@ -188,7 +191,7 @@ public class ESAdapter implements OuterAdapter {
// 取所有的destination为task的配置 // 取所有的destination为task的配置
if (configTmp.getDestination().equals(task)) { if (configTmp.getDestination().equals(task)) {
ESEtlService esEtlService = new ESEtlService(transportClient, configTmp); ESEtlService esEtlService = new ESEtlService(transportClient, configTmp);
EtlResult etlRes = esEtlService.importData(params, false); EtlResult etlRes = esEtlService.importData(params);
if (!etlRes.getSucceeded()) { if (!etlRes.getSucceeded()) {
resSuccess = false; resSuccess = false;
resultMsg.append(etlRes.getErrorMessage()).append("\n"); resultMsg.append(etlRes.getErrorMessage()).append("\n");

View File

@@ -30,7 +30,7 @@ public class ESSyncConfig {
if (esMapping._type == null) { if (esMapping._type == null) {
throw new NullPointerException("esMapping._type"); throw new NullPointerException("esMapping._type");
} }
if (esMapping._id == null && esMapping.pk == null) { if (esMapping._id == null && esMapping.getPk() == null) {
throw new NullPointerException("esMapping._id and esMapping.pk"); throw new NullPointerException("esMapping._id and esMapping.pk");
} }
if (esMapping.sql == null) { if (esMapping.sql == null) {
@@ -83,8 +83,9 @@ public class ESSyncConfig {
private String _index; private String _index;
private String _type; private String _type;
private String _id; private String _id;
private boolean upsert = false;
private String pk; private String pk;
private String parent; // private String parent;
private String sql; private String sql;
// 对象字段, 例: objFields: // 对象字段, 例: objFields:
// - _labels: array:; // - _labels: array:;
@@ -121,6 +122,14 @@ public class ESSyncConfig {
this._id = _id; this._id = _id;
} }
public boolean isUpsert() {
return upsert;
}
public void setUpsert(boolean upsert) {
this.upsert = upsert;
}
public String getPk() { public String getPk() {
return pk; return pk;
} }
@@ -129,14 +138,6 @@ public class ESSyncConfig {
this.pk = pk; this.pk = pk;
} }
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public Map<String, String> getObjFields() { public Map<String, String> getObjFields() {
return objFields; return objFields;
} }

View File

@@ -57,6 +57,11 @@ public class SchemaItem {
this.selectFields = selectFields; this.selectFields = selectFields;
} }
public String toSql() {
// todo
return null;
}
public Map<String, List<TableItem>> getTableItemAliases() { public Map<String, List<TableItem>> getTableItemAliases() {
if (tableItemAliases == null) { if (tableItemAliases == null) {
synchronized (SchemaItem.class) { synchronized (SchemaItem.class) {
@@ -316,6 +321,7 @@ public class SchemaItem {
public static class FieldItem { public static class FieldItem {
private String fieldName; private String fieldName;
private String expr;
private List<ColumnItem> columnItems = new ArrayList<>(); private List<ColumnItem> columnItems = new ArrayList<>();
private List<String> owners = new ArrayList<>(); private List<String> owners = new ArrayList<>();
@@ -330,6 +336,14 @@ public class SchemaItem {
this.fieldName = fieldName; this.fieldName = fieldName;
} }
public String getExpr() {
return expr;
}
public void setExpr(String expr) {
this.expr = expr;
}
public List<ColumnItem> getColumnItems() { public List<ColumnItem> getColumnItems() {
return columnItems; return columnItems;
} }

View File

@@ -74,6 +74,7 @@ public class SqlParser {
return sqlSelectQueryBlock.getSelectList().stream().map(selectItem -> { return sqlSelectQueryBlock.getSelectList().stream().map(selectItem -> {
FieldItem fieldItem = new FieldItem(); FieldItem fieldItem = new FieldItem();
fieldItem.setFieldName(selectItem.getAlias()); fieldItem.setFieldName(selectItem.getAlias());
fieldItem.setExpr(selectItem.toString());
visitColumn(selectItem.getExpr(), fieldItem); visitColumn(selectItem.getExpr(), fieldItem);
return fieldItem; return fieldItem;
}).collect(Collectors.toList()); }).collect(Collectors.toList());
@@ -91,6 +92,7 @@ public class SqlParser {
SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) expr; SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) expr;
if (fieldItem.getFieldName() == null) { if (fieldItem.getFieldName() == null) {
fieldItem.setFieldName(identifierExpr.getName()); fieldItem.setFieldName(identifierExpr.getName());
fieldItem.setExpr(identifierExpr.toString());
} }
ColumnItem columnItem = new ColumnItem(); ColumnItem columnItem = new ColumnItem();
columnItem.setColumnName(identifierExpr.getName()); columnItem.setColumnName(identifierExpr.getName());
@@ -101,6 +103,7 @@ public class SqlParser {
SQLPropertyExpr sqlPropertyExpr = (SQLPropertyExpr) expr; SQLPropertyExpr sqlPropertyExpr = (SQLPropertyExpr) expr;
if (fieldItem.getFieldName() == null) { if (fieldItem.getFieldName() == null) {
fieldItem.setFieldName(sqlPropertyExpr.getName()); fieldItem.setFieldName(sqlPropertyExpr.getName());
fieldItem.setExpr(sqlPropertyExpr.toString());
} }
fieldItem.getOwners().add(sqlPropertyExpr.getOwnernName()); fieldItem.getOwners().add(sqlPropertyExpr.getOwnernName());
ColumnItem columnItem = new ColumnItem(); ColumnItem columnItem = new ColumnItem();

View File

@@ -1,6 +1,9 @@
package com.alibaba.otter.canal.client.adapter.es.service; package com.alibaba.otter.canal.client.adapter.es.service;
import java.util.*; import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@@ -14,7 +17,9 @@ import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus; import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHit;
@@ -51,7 +56,7 @@ public class ESEtlService {
this.config = config; this.config = config;
} }
public EtlResult importData(List<String> params, boolean bulk) { public EtlResult importData(List<String> params) {
EtlResult etlResult = new EtlResult(); EtlResult etlResult = new EtlResult();
AtomicLong impCount = new AtomicLong(); AtomicLong impCount = new AtomicLong();
List<String> errMsg = new ArrayList<>(); List<String> errMsg = new ArrayList<>();
@@ -93,54 +98,49 @@ public class ESEtlService {
logger.debug("etl sql : {}", mapping.getSql()); logger.debug("etl sql : {}", mapping.getSql());
} }
if (bulk) { // 获取总数
// 获取总数 String countSql = "SELECT COUNT(1) FROM ( " + sql + ") _CNT ";
String countSql = "SELECT COUNT(1) FROM ( " + sql + ") _CNT "; long cnt = (Long) ESSyncUtil.sqlRS(dataSource, countSql, rs -> {
long cnt = (Long) ESSyncUtil.sqlRS(dataSource, countSql, rs -> { Long count = null;
Long count = null; try {
try { if (rs.next()) {
if (rs.next()) { count = ((Number) rs.getObject(1)).longValue();
count = ((Number) rs.getObject(1)).longValue();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
} }
return count == null ? 0L : count; } catch (Exception e) {
}); logger.error(e.getMessage(), e);
// 当大于1万条记录时开启多线程
if (cnt >= 10000) {
int threadCount = 3; // TODO 从配置读取默认为3
long perThreadCnt = cnt / threadCount;
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
List<Future<Boolean>> futures = new ArrayList<>(threadCount);
for (int i = 0; i < threadCount; i++) {
long offset = i * perThreadCnt;
Long size = null;
if (i != threadCount - 1) {
size = perThreadCnt;
}
String sqlFinal;
if (size != null) {
sqlFinal = sql + " LIMIT " + offset + "," + size;
} else {
sqlFinal = sql + " LIMIT " + offset + "," + cnt;
}
Future<Boolean> future = executor
.submit(() -> executeSqlImport(dataSource, sqlFinal, mapping, impCount, errMsg));
futures.add(future);
}
for (Future<Boolean> future : futures) {
future.get();
}
executor.shutdown();
} else {
executeSqlImport(dataSource, sql, mapping, impCount, errMsg);
} }
return count == null ? 0L : count;
});
// 当大于1万条记录时开启多线程
if (cnt >= 10000) {
int threadCount = 3; // 从配置读取默认为3
long perThreadCnt = cnt / threadCount;
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
List<Future<Boolean>> futures = new ArrayList<>(threadCount);
for (int i = 0; i < threadCount; i++) {
long offset = i * perThreadCnt;
Long size = null;
if (i != threadCount - 1) {
size = perThreadCnt;
}
String sqlFinal;
if (size != null) {
sqlFinal = sql + " LIMIT " + offset + "," + size;
} else {
sqlFinal = sql + " LIMIT " + offset + "," + cnt;
}
Future<Boolean> future = executor
.submit(() -> executeSqlImport(dataSource, sqlFinal, mapping, impCount, errMsg));
futures.add(future);
}
for (Future<Boolean> future : futures) {
future.get();
}
executor.shutdown();
} else { } else {
logger.info("自动ETL,无需统计记录总条数,直接进行ETL, index: {}", esIndex);
executeSqlImport(dataSource, sql, mapping, impCount, errMsg); executeSqlImport(dataSource, sql, mapping, impCount, errMsg);
} }
@@ -158,7 +158,7 @@ public class ESEtlService {
return etlResult; return etlResult;
} }
private void processFailBulkResponse(BulkResponse bulkResponse, boolean hasParent) { private void processFailBulkResponse(BulkResponse bulkResponse) {
for (BulkItemResponse response : bulkResponse.getItems()) { for (BulkItemResponse response : bulkResponse.getItems()) {
if (!response.isFailed()) { if (!response.isFailed()) {
continue; continue;
@@ -205,31 +205,27 @@ public class ESEtlService {
} }
if (idVal != null) { if (idVal != null) {
if (mapping.getParent() == null) { if (mapping.isUpsert()) {
bulkRequestBuilder.add(transportClient
.prepareUpdate(mapping.get_index(), mapping.get_type(), idVal.toString())
.setDoc(esFieldData)
.setDocAsUpsert(true));
} else {
bulkRequestBuilder.add(transportClient bulkRequestBuilder.add(transportClient
.prepareIndex(mapping.get_index(), mapping.get_type(), idVal.toString()) .prepareIndex(mapping.get_index(), mapping.get_type(), idVal.toString())
.setSource(esFieldData)); .setSource(esFieldData));
} else {
// ignore
} }
} else { } else {
idVal = rs.getObject(mapping.getPk()); idVal = rs.getObject(mapping.getPk());
if (mapping.getParent() == null) { SearchResponse response = transportClient.prepareSearch(mapping.get_index())
// 删除pk对应的数据 .setTypes(mapping.get_type())
SearchResponse response = transportClient.prepareSearch(mapping.get_index()) .setQuery(QueryBuilders.termQuery(mapping.getPk(), idVal))
.setTypes(mapping.get_type()) .setSize(10000)
.setQuery(QueryBuilders.termQuery(mapping.getPk(), idVal)) .get();
.get(); for (SearchHit hit : response.getHits()) {
for (SearchHit hit : response.getHits()) { bulkRequestBuilder.add(
bulkRequestBuilder.add(transportClient transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), hit.getId())
.prepareDelete(mapping.get_index(), mapping.get_type(), hit.getId())); .setDoc(esFieldData));
}
bulkRequestBuilder
.add(transportClient.prepareIndex(mapping.get_index(), mapping.get_type())
.setSource(esFieldData));
} else {
// ignore
} }
} }
@@ -238,11 +234,11 @@ public class ESEtlService {
long esBatchBegin = System.currentTimeMillis(); long esBatchBegin = System.currentTimeMillis();
BulkResponse rp = bulkRequestBuilder.execute().actionGet(); BulkResponse rp = bulkRequestBuilder.execute().actionGet();
if (rp.hasFailures()) { if (rp.hasFailures()) {
this.processFailBulkResponse(rp, Objects.nonNull(mapping.getParent())); this.processFailBulkResponse(rp);
} }
if (logger.isDebugEnabled()) { if (logger.isTraceEnabled()) {
logger.debug("全量数据批量导入批次耗时: {}, es执行时间: {}, 批次大小: {}, index; {}", logger.trace("全量数据批量导入批次耗时: {}, es执行时间: {}, 批次大小: {}, index; {}",
(System.currentTimeMillis() - batchBegin), (System.currentTimeMillis() - batchBegin),
(System.currentTimeMillis() - esBatchBegin), (System.currentTimeMillis() - esBatchBegin),
bulkRequestBuilder.numberOfActions(), bulkRequestBuilder.numberOfActions(),
@@ -259,10 +255,10 @@ public class ESEtlService {
long esBatchBegin = System.currentTimeMillis(); long esBatchBegin = System.currentTimeMillis();
BulkResponse rp = bulkRequestBuilder.execute().actionGet(); BulkResponse rp = bulkRequestBuilder.execute().actionGet();
if (rp.hasFailures()) { if (rp.hasFailures()) {
this.processFailBulkResponse(rp, Objects.nonNull(mapping.getParent())); this.processFailBulkResponse(rp);
} }
if (logger.isDebugEnabled()) { if (logger.isTraceEnabled()) {
logger.debug("全量数据批量导入最后批次耗时: {}, es执行时间: {}, 批次大小: {}, index; {}", logger.trace("全量数据批量导入最后批次耗时: {}, es执行时间: {}, 批次大小: {}, index; {}",
(System.currentTimeMillis() - batchBegin), (System.currentTimeMillis() - batchBegin),
(System.currentTimeMillis() - esBatchBegin), (System.currentTimeMillis() - esBatchBegin),
bulkRequestBuilder.numberOfActions(), bulkRequestBuilder.numberOfActions(),

View File

@@ -71,7 +71,12 @@ public class ESSyncService {
dml.getDestination()); dml.getDestination());
} }
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("DML: {}", JSON.toJSONString(dml, SerializerFeature.WriteMapNullValue)); StringBuilder configIndexes = new StringBuilder();
esSyncConfigs
.forEach(esSyncConfig -> configIndexes.append(esSyncConfig.getEsMapping().get_index()).append(" "));
logger.debug("DML: {} \nEffect indexes: {}",
JSON.toJSONString(dml, SerializerFeature.WriteMapNullValue),
configIndexes.toString());
} }
} }
} }
@@ -92,6 +97,8 @@ public class ESSyncService {
update(config, dml); update(config, dml);
} else if (type != null && type.equalsIgnoreCase("DELETE")) { } else if (type != null && type.equalsIgnoreCase("DELETE")) {
delete(config, dml); delete(config, dml);
} else {
return;
} }
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
@@ -329,33 +336,50 @@ public class ESSyncService {
// ------是主表------ // ------是主表------
if (schemaItem.getMainTable().getTableName().equalsIgnoreCase(dml.getTable())) { if (schemaItem.getMainTable().getTableName().equalsIgnoreCase(dml.getTable())) {
FieldItem idFieldItem = schemaItem.getIdFieldItem(mapping); if (mapping.get_id() != null) {
// 主键为简单字段 FieldItem idFieldItem = schemaItem.getIdFieldItem(mapping);
if (!idFieldItem.isMethod() && !idFieldItem.isBinaryOp()) { // 主键为简单字段
Object idVal = esTemplate.getValFromData(mapping, if (!idFieldItem.isMethod() && !idFieldItem.isBinaryOp()) {
data, Object idVal = esTemplate.getValFromData(mapping,
idFieldItem.getFieldName(), data,
idFieldItem.getColumn().getColumnName()); idFieldItem.getFieldName(),
idFieldItem.getColumn().getColumnName());
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
logger.trace("Main table delete es index, destination:{}, table: {}, index: {}, id: {}", logger.trace("Main table delete es index, destination:{}, table: {}, index: {}, id: {}",
config.getDestination(), config.getDestination(),
dml.getTable(), dml.getTable(),
mapping.get_index(), mapping.get_index(),
idVal); idVal);
} }
boolean result = esTemplate.delete(mapping, idVal); esTemplate.delete(mapping, idVal, null);
if (!result) { } else {
logger.error("Main table delete es index error, destination:{}, table: {}, index: {}, id: {}", // ------主键带函数, 查询sql获取主键删除------
config.getDestination(), // FIXME 删除时反查sql为空记录, 无法获获取 id field 值
dml.getTable(), mainTableDelete(config, dml, data);
mapping.get_index(),
idVal);
} }
} else { } else {
// ------主键带函数, 查询sql获取主键删除------ FieldItem pkFieldItem = schemaItem.getIdFieldItem(mapping);
mainTableDelete(config, dml, data); if (!pkFieldItem.isMethod() && !pkFieldItem.isBinaryOp()) {
Map<String, Object> esFieldData = new LinkedHashMap<>();
Object pkVal = esTemplate.getESDataFromDmlData(mapping, data, esFieldData);
if (logger.isTraceEnabled()) {
logger.trace("Main table delete es index, destination:{}, table: {}, index: {}, pk: {}",
config.getDestination(),
dml.getTable(),
mapping.get_index(),
pkVal);
}
esFieldData.remove(pkFieldItem.getFieldName());
esFieldData.keySet().forEach(key -> esFieldData.put(key, null));
esTemplate.delete(mapping, pkVal, esFieldData);
} else {
// ------主键带函数, 查询sql获取主键删除------
mainTableDelete(config, dml, data);
}
} }
} }
// 从表的操作 // 从表的操作
@@ -417,14 +441,7 @@ public class ESSyncService {
mapping.get_index(), mapping.get_index(),
idVal); idVal);
} }
boolean result = esTemplate.insert(mapping, idVal, esFieldData); esTemplate.insert(mapping, idVal, esFieldData);
if (!result) {
logger.error("Single table insert to es index error, destination:{}, table: {}, index: {}, id: {}",
config.getDestination(),
dml.getTable(),
mapping.get_index(),
idVal);
}
} }
/** /**
@@ -461,15 +478,7 @@ public class ESSyncService {
mapping.get_index(), mapping.get_index(),
idVal); idVal);
} }
boolean result = esTemplate.insert(mapping, idVal, esFieldData); esTemplate.insert(mapping, idVal, esFieldData);
if (!result) {
logger.error(
"Main table insert to es index by query sql error, destination:{}, table: {}, index: {}, id: {}",
config.getDestination(),
dml.getTable(),
mapping.get_index(),
idVal);
}
} }
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@@ -493,6 +502,15 @@ public class ESSyncService {
} }
ESSyncUtil.sqlRS(ds, sql, rs -> { ESSyncUtil.sqlRS(ds, sql, rs -> {
try { try {
Map<String, Object> esFieldData = null;
if (mapping.getPk() != null) {
esFieldData = new LinkedHashMap<>();
esTemplate.getESDataFromDmlData(mapping, data, esFieldData);
esFieldData.remove(mapping.getPk());
for (String key : esFieldData.keySet()) {
esFieldData.put(key, null);
}
}
while (rs.next()) { while (rs.next()) {
Object idVal = esTemplate.getIdValFromRS(mapping, rs); Object idVal = esTemplate.getIdValFromRS(mapping, rs);
@@ -504,15 +522,7 @@ public class ESSyncService {
mapping.get_index(), mapping.get_index(),
idVal); idVal);
} }
boolean result = esTemplate.delete(mapping, idVal); esTemplate.delete(mapping, idVal, esFieldData);
if (!result) {
logger.error(
"Main table delete to es index by query sql error, destination:{}, table: {}, index: {}, id: {}",
config.getDestination(),
dml.getTable(),
mapping.get_index(),
idVal);
}
} }
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@@ -558,13 +568,7 @@ public class ESSyncService {
dml.getTable(), dml.getTable(),
mapping.get_index()); mapping.get_index());
} }
boolean result = esTemplate.updateByQuery(config, paramsTmp, esFieldData); esTemplate.updateByQuery(config, paramsTmp, esFieldData);
if (!result) {
logger.error("Join table update es index by foreign key error, destination:{}, table: {}, index: {}",
config.getDestination(),
dml.getTable(),
mapping.get_index());
}
} }
/** /**
@@ -652,14 +656,7 @@ public class ESSyncService {
dml.getTable(), dml.getTable(),
mapping.get_index()); mapping.get_index());
} }
boolean result = esTemplate.updateByQuery(config, paramsTmp, esFieldData); esTemplate.updateByQuery(config, paramsTmp, esFieldData);
if (!result) {
logger.error(
"Join table update es index by query sql error, destination:{}, table: {}, index: {}",
config.getDestination(),
dml.getTable(),
mapping.get_index());
}
} }
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@@ -761,14 +758,7 @@ public class ESSyncService {
dml.getTable(), dml.getTable(),
mapping.get_index()); mapping.get_index());
} }
boolean result = esTemplate.updateByQuery(config, paramsTmp, esFieldData); esTemplate.updateByQuery(config, paramsTmp, esFieldData);
if (!result) {
logger.error(
"Join table update es index by query whole sql error, destination:{}, table: {}, index: {}",
config.getDestination(),
dml.getTable(),
mapping.get_index());
}
} }
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@@ -799,14 +789,7 @@ public class ESSyncService {
mapping.get_index(), mapping.get_index(),
idVal); idVal);
} }
boolean result = esTemplate.update(mapping, idVal, esFieldData); esTemplate.update(mapping, idVal, esFieldData);
if (!result) {
logger.error("Main table update to es index error, destination:{}, table: {}, index: {}, id: {}",
config.getDestination(),
dml.getTable(),
mapping.get_index(),
idVal);
}
} }
/** /**
@@ -843,15 +826,7 @@ public class ESSyncService {
mapping.get_index(), mapping.get_index(),
idVal); idVal);
} }
boolean result = esTemplate.update(mapping, idVal, esFieldData); esTemplate.update(mapping, idVal, esFieldData);
if (!result) {
logger.error(
"Main table update to es index by query sql error, destination:{}, table: {}, index: {}, id: {}",
config.getDestination(),
dml.getTable(),
mapping.get_index(),
idVal);
}
} }
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@@ -859,4 +834,11 @@ public class ESSyncService {
return 0; return 0;
}); });
} }
/**
* 提交批次
*/
public void commit() {
esTemplate.commit();
}
} }

View File

@@ -2,14 +2,13 @@ package com.alibaba.otter.canal.client.adapter.es.support;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource; import javax.sql.DataSource;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.bulk.BulkResponse;
@@ -18,18 +17,11 @@ import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.UpdateByQueryAction;
import org.elasticsearch.index.reindex.UpdateByQueryRequestBuilder;
import org.elasticsearch.rest.RestStatus; import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHit;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import com.alibaba.otter.canal.client.adapter.es.config.ESSyncConfig; import com.alibaba.otter.canal.client.adapter.es.config.ESSyncConfig;
import com.alibaba.otter.canal.client.adapter.es.config.ESSyncConfig.ESMapping; import com.alibaba.otter.canal.client.adapter.es.config.ESSyncConfig.ESMapping;
@@ -52,254 +44,135 @@ public class ESTemplate {
private TransportClient transportClient; private TransportClient transportClient;
private BulkRequestBuilder bulkRequestBuilder;
public ESTemplate(TransportClient transportClient){ public ESTemplate(TransportClient transportClient){
this.transportClient = transportClient; this.transportClient = transportClient;
this.bulkRequestBuilder = transportClient.prepareBulk();
}
public BulkRequestBuilder getBulk() {
return bulkRequestBuilder;
} }
/** /**
* 插入数据 * 插入数据
* *
* @param mapping * @param mapping 配置对象
* @param pkVal * @param pkVal 主键值
* @param esFieldData * @param esFieldData 数据Map
* @return
*/ */
public boolean insert(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) { public void insert(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) {
BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
if (mapping.get_id() != null) { if (mapping.get_id() != null) {
bulkRequestBuilder if (mapping.isUpsert()) {
.add(transportClient.prepareIndex(mapping.get_index(), mapping.get_type(), pkVal.toString()) getBulk().add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), pkVal.toString())
.setDoc(esFieldData)
.setDocAsUpsert(true));
} else {
getBulk().add(transportClient.prepareIndex(mapping.get_index(), mapping.get_type(), pkVal.toString())
.setSource(esFieldData)); .setSource(esFieldData));
}
commitBulk();
} else { } else {
SearchResponse response = transportClient.prepareSearch(mapping.get_index()) SearchResponse response = transportClient.prepareSearch(mapping.get_index())
.setTypes(mapping.get_type()) .setTypes(mapping.get_type())
.setQuery(QueryBuilders.termQuery(mapping.getPk(), pkVal)) .setQuery(QueryBuilders.termQuery(mapping.getPk(), pkVal))
.setSize(MAX_BATCH_SIZE) .setSize(10000)
.get(); .get();
for (SearchHit hit : response.getHits()) { for (SearchHit hit : response.getHits()) {
bulkRequestBuilder getBulk().add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), hit.getId())
.add(transportClient.prepareDelete(mapping.get_index(), mapping.get_type(), hit.getId())); .setDoc(esFieldData));
commitBulk();
} }
bulkRequestBuilder
.add(transportClient.prepareIndex(mapping.get_index(), mapping.get_type()).setSource(esFieldData));
} }
return commitBulkRequest(bulkRequestBuilder);
} }
/** /**
* 根据主键更新数据 * 根据主键更新数据
* *
* @param mapping * @param mapping 配置对象
* @param pkVal * @param pkVal 主键值
* @param esFieldData * @param esFieldData 数据Map
* @return
*/ */
public boolean update(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) { public void update(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) {
BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk(); append4Update(mapping, pkVal, esFieldData);
append4Update(bulkRequestBuilder, mapping, pkVal, esFieldData); commitBulk();
return commitBulkRequest(bulkRequestBuilder);
}
public void append4Update(BulkRequestBuilder bulkRequestBuilder, ESMapping mapping, Object pkVal,
Map<String, Object> esFieldData) {
if (mapping.get_id() != null) {
bulkRequestBuilder
.add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), pkVal.toString())
.setDoc(esFieldData));
} else {
SearchResponse response = transportClient.prepareSearch(mapping.get_index())
.setTypes(mapping.get_type())
.setQuery(QueryBuilders.termQuery(mapping.getPk(), pkVal))
.setSize(MAX_BATCH_SIZE)
.get();
for (SearchHit hit : response.getHits()) {
bulkRequestBuilder
.add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), hit.getId())
.setDoc(esFieldData));
}
}
} }
/** /**
* update by query * update by query
* *
* @param config * @param config 配置对象
* @param paramsTmp * @param paramsTmp sql查询条件
* @param esFieldData * @param esFieldData 数据Map
* @return
*/ */
public boolean updateByQuery(ESSyncConfig config, Map<String, Object> paramsTmp, Map<String, Object> esFieldData) { public void updateByQuery(ESSyncConfig config, Map<String, Object> paramsTmp, Map<String, Object> esFieldData) {
if (paramsTmp.isEmpty()) { if (paramsTmp.isEmpty()) {
return false; return;
} }
ESMapping mapping = config.getEsMapping(); ESMapping mapping = config.getEsMapping();
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery(); BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
paramsTmp.forEach((fieldName, value) -> queryBuilder.must(QueryBuilders.termsQuery(fieldName, value))); paramsTmp.forEach((fieldName, value) -> queryBuilder.must(QueryBuilders.termsQuery(fieldName, value)));
SearchResponse response = transportClient.prepareSearch(mapping.get_index()) // 查询sql批量更新
.setTypes(mapping.get_type()) DataSource ds = DatasourceConfig.DATA_SOURCES.get(config.getDataSourceKey());
.setSize(0) StringBuilder sql = new StringBuilder("SELECT * FROM (" + mapping.getSql() + ") _v WHERE ");
.setQuery(queryBuilder) paramsTmp.forEach(
.get(); (fieldName, value) -> sql.append("_v.").append(fieldName).append("=").append(value).append(" AND "));
long count = response.getHits().getTotalHits(); int len = sql.length();
// 如果更新量大于Max, 查询sql批量更新 sql.delete(len - 4, len);
if (count > MAX_BATCH_SIZE) { Integer syncCount = (Integer) ESSyncUtil.sqlRS(ds, sql.toString(), rs -> {
BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk(); int count = 0;
DataSource ds = DatasourceConfig.DATA_SOURCES.get(config.getDataSourceKey());
// 查询sql更新
StringBuilder sql = new StringBuilder("SELECT * FROM (" + mapping.getSql() + ") _v WHERE ");
paramsTmp.forEach(
(fieldName, value) -> sql.append("_v.").append(fieldName).append("=").append(value).append(" AND "));
int len = sql.length();
sql.delete(len - 4, len);
ESSyncUtil.sqlRS(ds, sql.toString(), rs -> {
int exeCount = 1;
try {
BulkRequestBuilder bulkRequestBuilderTmp = bulkRequestBuilder;
while (rs.next()) {
Object idVal = getIdValFromRS(mapping, rs);
append4Update(bulkRequestBuilderTmp, mapping, idVal, esFieldData);
if (exeCount % mapping.getCommitBatch() == 0 && bulkRequestBuilderTmp.numberOfActions() > 0) {
commitBulkRequest(bulkRequestBuilderTmp);
bulkRequestBuilderTmp = transportClient.prepareBulk();
}
exeCount++;
}
if (bulkRequestBuilder.numberOfActions() > 0) {
commitBulkRequest(bulkRequestBuilderTmp);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return 0;
});
return true;
} else {
return updateByQuery(mapping, queryBuilder, esFieldData, 1);
}
}
private boolean updateByQuery(ESMapping mapping, QueryBuilder queryBuilder, Map<String, Object> esFieldData,
int counter) {
if (CollectionUtils.isEmpty(esFieldData)) {
return true;
}
StringBuilder sb = new StringBuilder();
esFieldData.forEach((key, value) -> {
if (value instanceof Map) {
Map<?, ?> mapValue = (Map<?, ?>) value;
if (mapValue.containsKey("lon") && mapValue.containsKey("lat") && mapValue.size() == 2) {
sb.append("ctx._source")
.append("['")
.append(key)
.append("']")
.append(" = [")
.append(mapValue.get("lon"))
.append(", ")
.append(mapValue.get("lat"))
.append("];");
} else {
sb.append("ctx._source").append("[\"").append(key).append("\"]").append(" = ");
sb.append(JSON.toJSONString(value));
sb.append(";");
}
} else if (value instanceof List) {
sb.append("ctx._source").append("[\"").append(key).append("\"]").append(" = ");
sb.append(JSON.toJSONString(value));
sb.append(";");
} else if (value instanceof String) {
sb.append("ctx._source")
.append("['")
.append(key)
.append("']")
.append(" = '")
.append(value)
.append("';");
} else {
sb.append("ctx._source").append("['").append(key).append("']").append(" = ").append(value).append(";");
}
});
String scriptLine = sb.toString();
if (logger.isTraceEnabled()) {
logger.trace(scriptLine);
}
UpdateByQueryRequestBuilder updateByQuery = UpdateByQueryAction.INSTANCE.newRequestBuilder(transportClient);
updateByQuery.source(mapping.get_index())
.abortOnVersionConflict(false)
.filter(queryBuilder)
.script(new Script(ScriptType.INLINE, "painless", scriptLine, Collections.emptyMap()));
BulkByScrollResponse response = updateByQuery.get();
if (logger.isTraceEnabled()) {
logger.trace("updateByQuery response: {}", response.getStatus());
}
if (!CollectionUtils.isEmpty(response.getSearchFailures())) {
logger.error("script update_for_search has search error: " + response.getBulkFailures());
return false;
}
if (!CollectionUtils.isEmpty(response.getBulkFailures())) {
logger.error("script update_for_search has update error: " + response.getBulkFailures());
return false;
}
if (response.getStatus().getVersionConflicts() > 0) {
if (counter >= 3) {
logger.error("第 {} 次执行updateByQuery, 依旧存在分片版本冲突,不再继续重试。", counter);
return false;
}
logger.warn("本次updateByQuery存在分片版本冲突,准备重新执行...");
try { try {
TimeUnit.SECONDS.sleep(1); while (rs.next()) {
} catch (InterruptedException e) { Object idVal = getIdValFromRS(mapping, rs);
// ignore append4Update(mapping, idVal, esFieldData);
commitBulk();
count++;
}
} catch (Exception e) {
throw new RuntimeException(e);
} }
return updateByQuery(mapping, queryBuilder, esFieldData, ++counter); return count;
});
if (logger.isTraceEnabled()) {
logger.trace("Update ES by query effect {} records", syncCount);
} }
return true;
} }
/** /**
* 通过主键删除数据 * 通过主键删除数据
* *
* @param mapping * @param mapping 配置对象
* @param pkVal * @param pkVal 主键值
* @return * @param esFieldData 数据Map
*/ */
public boolean delete(ESMapping mapping, Object pkVal) { public void delete(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) {
BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
if (mapping.get_id() != null) { if (mapping.get_id() != null) {
bulkRequestBuilder getBulk().add(transportClient.prepareDelete(mapping.get_index(), mapping.get_type(), pkVal.toString()));
.add(transportClient.prepareDelete(mapping.get_index(), mapping.get_type(), pkVal.toString())); commitBulk();
} else { } else {
SearchResponse response = transportClient.prepareSearch(mapping.get_index()) SearchResponse response = transportClient.prepareSearch(mapping.get_index())
.setTypes(mapping.get_type()) .setTypes(mapping.get_type())
.setQuery(QueryBuilders.termQuery(mapping.getPk(), pkVal)) .setQuery(QueryBuilders.termQuery(mapping.getPk(), pkVal))
.setSize(MAX_BATCH_SIZE) .setSize(10000)
.get(); .get();
for (SearchHit hit : response.getHits()) { for (SearchHit hit : response.getHits()) {
bulkRequestBuilder getBulk().add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), hit.getId())
.add(transportClient.prepareDelete(mapping.get_index(), mapping.get_type(), hit.getId())); .setDoc(esFieldData));
commitBulk();
} }
} }
return commitBulkRequest(bulkRequestBuilder);
} }
/** /**
* 批量提交 * 提交批次
*
* @param bulkRequestBuilder
* @return
*/ */
private static boolean commitBulkRequest(BulkRequestBuilder bulkRequestBuilder) { public void commit() {
if (bulkRequestBuilder.numberOfActions() > 0) { if (getBulk().numberOfActions() > 0) {
BulkResponse response = bulkRequestBuilder.execute().actionGet(); BulkResponse response = getBulk().execute().actionGet();
if (response.hasFailures()) { if (response.hasFailures()) {
for (BulkItemResponse itemResponse : response.getItems()) { for (BulkItemResponse itemResponse : response.getItems()) {
if (!itemResponse.isFailed()) { if (!itemResponse.isFailed()) {
@@ -307,16 +180,45 @@ public class ESTemplate {
} }
if (itemResponse.getFailure().getStatus() == RestStatus.NOT_FOUND) { if (itemResponse.getFailure().getStatus() == RestStatus.NOT_FOUND) {
logger.warn(itemResponse.getFailureMessage()); logger.error(itemResponse.getFailureMessage());
} else { } else {
logger.error("ES sync commit error: {}", itemResponse.getFailureMessage()); throw new RuntimeException("ES sync commit error" + itemResponse.getFailureMessage());
} }
} }
} }
return !response.hasFailures();
} }
return true; }
/**
* 如果大于批量数则提交批次
*/
private void commitBulk() {
if (getBulk().numberOfActions() >= MAX_BATCH_SIZE) {
commit();
}
}
private void append4Update(ESMapping mapping, Object pkVal, Map<String, Object> esFieldData) {
if (mapping.get_id() != null) {
if (mapping.isUpsert()) {
getBulk().add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), pkVal.toString())
.setDoc(esFieldData)
.setDocAsUpsert(true));
} else {
getBulk().add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), pkVal.toString())
.setDoc(esFieldData));
}
} else {
SearchResponse response = transportClient.prepareSearch(mapping.get_index())
.setTypes(mapping.get_type())
.setQuery(QueryBuilders.termQuery(mapping.getPk(), pkVal))
.setSize(10000)
.get();
for (SearchHit hit : response.getHits()) {
getBulk().add(transportClient.prepareUpdate(mapping.get_index(), mapping.get_type(), hit.getId())
.setDoc(esFieldData));
}
}
} }
public Object getValFromRS(ESMapping mapping, ResultSet resultSet, String fieldName, public Object getValFromRS(ESMapping mapping, ResultSet resultSet, String fieldName,

View File

@@ -5,6 +5,7 @@ esMapping:
_index: mytest_user _index: mytest_user
_type: _doc _type: _doc
_id: _id _id: _id
upsert: true
# pk: id # pk: id
sql: "select a.id as _id, a.name as _name, a.role_id as _role_id, b.role_name as _role_name, sql: "select a.id as _id, a.name as _name, a.role_id as _role_id, b.role_name as _role_name,
a.c_time as _c_time from user a a.c_time as _c_time from user a

View File

@@ -29,7 +29,7 @@ public class SqlParseTest {
Assert.assertFalse(tableItem.isMain()); Assert.assertFalse(tableItem.isMain());
Assert.assertTrue(tableItem.isSubQuery()); Assert.assertTrue(tableItem.isSubQuery());
// 通过字段名找 FieldItem // 通过字段名找 FieldItem
List<FieldItem> fieldItems = schemaItem.getColumnFields().get(tableItem.getAlias() + ".label".toLowerCase()); List<FieldItem> fieldItems = schemaItem.getColumnFields().get(tableItem.getAlias() + ".labels".toLowerCase());
fieldItems.forEach( fieldItems.forEach(
fieldItem -> Assert.assertEquals("c.labels", fieldItem.getOwner() + "." + fieldItem.getFieldName())); fieldItem -> Assert.assertEquals("c.labels", fieldItem.getOwner() + "." + fieldItem.getFieldName()));

View File

@@ -52,16 +52,17 @@ public class BatchExecutor implements Closeable {
} }
public void execute(String sql, List<Map<String, ?>> values) throws SQLException { public void execute(String sql, List<Map<String, ?>> values) throws SQLException {
PreparedStatement pstmt = getConn().prepareStatement(sql); try (PreparedStatement pstmt = getConn().prepareStatement(sql)) {
int len = values.size(); int len = values.size();
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
int type = (Integer) values.get(i).get("type"); int type = (Integer) values.get(i).get("type");
Object value = values.get(i).get("value"); Object value = values.get(i).get("value");
SyncUtil.setPStmt(type, pstmt, value, i + 1); SyncUtil.setPStmt(type, pstmt, value, i + 1);
} }
pstmt.execute(); pstmt.execute();
idx.incrementAndGet(); idx.incrementAndGet();
}
} }
public void commit() throws SQLException { public void commit() throws SQLException {