本文主要是介绍Java使用ElasticSearch API设置Mapping,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近一个项目要接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和接入的代码如下:
@Overridepublic 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();}//写入数据到ElasticSearchIndexRequestBuilder 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 API设置Mapping的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!