您的位置:首页 > 移动开发

Java使用ElasticSearch API设置Mapping

2017-07-25 10:59 591 查看
最近一个项目要接PLC下位机的数据存放到ElasticSearch,数据都是double的数值类型,因此在接的时候需要进行Mapping:

"rEva_Photo_x2": {
"type": "double"
},
"AlarmbAlignConvInverter": {
"type": "double"
},
"AlarmbAlignConvLoseErr": {
"type": "double"
},
"AlarmbAlignFor": {
"type": "double"
},
"AlarmbInConvLoseErr": {
"type": "double"
},
"AlarmbLowerlimit": {
"type": "double"
},................ 设置Mapping和接入的代码如下:
@Override
public void saveAideEs(SaveAideEs saveAideEs) {

IndicesExistsResponse indicesResponse =
getClient().admin().indices().exists(
new IndicesExistsRequest().indices(new String[]{saveAideEs.getIndex()})).actionGet();
//如果Index不存在就创建Mapping会报错
if(!indicesResponse.isExists()) {
getClient().admin().indices().prepareCreate(saveAideEs.getIndex()).execute().actionGet();
PutMappingRequest mapping = Requests.putMappingRequest(saveAideEs.getIndex()).type(saveAideEs.getType()).
source(getMapping(saveAideEs.getSource().keySet()));
getClient().admin().indices().putMapping(mapping).actionGet();
}
//写入数据到ElasticSearch
IndexRequestBuilder builder = getClient().prepareIndex(saveAideEs.getIndex(), saveAideEs.getType());
builder.setSource(saveAideEs.getSource());
builder.get();
}
//构造Mapping,keySet包含所有的字段
private XContentBuilder getMapping(Set<String> keySet) {
XContentBuilder mapping = null;
try {
mapping = jsonBuilder()
.startObject().startObject("properties");
Iterator<String> it = keySet.iterator();
while (it.hasNext()) {
String str = it.next();
if(str.equals("@timestamp")) //跳过@timestamp字段
continue;
mapping.startObject(str).field("type", "double").field("index","not_analyzed").endObject();
}
mapping.endObject().endObject();
} catch (IOException e) {
e.printStackTrace();
}
return mapping;
} 之后就可以对这些字段进行数值运算了,下面是个使用ElasticSearch-sql的例子:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java ElasticSearch