elasticsearch 自定义ID
场景描述
es采集关系型数据库(mysql)中的数据 进行id 精准搜索, 由于mysql 中的ID 生成规则为 分布式ID(19位 ) 使用 long 类型接收并写入到es 中 会有精度的丢失 (es 版本 5.5.3 )
es采集核心代码
public static void insertOne(String index, String type, Object object) {
if (object != null) {
try {
Map<String, Object> objMap = (Map<String, Object>) JSON.toJSON(object);
try {
IndexRequest indexRequest = new IndexRequest(index, type, objMap.get("id").toString());
indexRequest.source(objMap);
highLevelClient.indexAsync(indexRequest, RequestOptions.DEFAULT, new ActionListener<IndexResponse>() {
@Override
public void onResponse(IndexResponse indexResponse) {
}
@Override
public void onFailure(Exception e) {
HttpUtil.sendError2SLS(e.getLocalizedMessage(), "es insert one actionListener failure");
}
});
} catch (Exception e) {
HttpUtil.sendError2SLS(e.getLocalizedMessage(), "es insert one ");
}
} catch (Exception e) {
HttpUtil.sendError2SLS(e.getLocalizedMessage(), "es insert one ");
}
}
}
问题描述
inertOne 方法中的参数对象都有一个 标量元素 long id ;
当数据插入到 es 中时 由于 关系型数据库(mysql)中的id 为 bigint 类型 写入到es 中的 id
精度有损失,故 通过 must termQuery 查询id 时 总是得不到数据 ,
解决方案
将对象中的 id 类型从long 类型转换为 String 类型 这样就保证了 写入到es中的数据中 _id 和 id 字段
的数据值是一样的 ,经过测试也可以使用 id 查询