看,灰机...

XContentBuilder 通过for循环执行,创建索引mappin结构

Elasticsearch | 作者 jianjianhe | 发布于2017年10月27日 | 阅读数:17844

 client = ESUtils.ES_UTILS.getClient();

XContentBuilder builder= XContentFactory.jsonBuilder()
.startObject()
.startObject(type)
.startObject("properties")
.startObject("user")
.field("type","string")
.field("index","not_analyzed")
.endObject()
.startObject("postDate")
.field("type","date")
.endObject()
.startObject("message")
.field("type","string")
.field("index","not_analyzed")
.endObject()
.startObject("address")
.field("type","string")
.endObject()
.startObject("车牌号")
.field("type","string")
.field("index","ik")
.endObject()
.endObject()
.endObject();


String mappingStr=builder.string();

client.admin().indices().prepareCreate(indexName).addMapping(type,mappingStr).setSettings(settings).execute();
因为后续索引字段还要增多,怎么通过for循环构建索引的mapping结构?
 
已邀请:

jianjianhe

赞同来自:

刚自己实现了,但写的很丑,顺便放上来吧,不知道是否有更简洁的办法,等大神指导!
 
  public void createIndex(String indexName, String type, Map<String, Map<String, String>> proNames, Map<String,Object> settings) throws IOException {

XContentBuilder builder = XContentFactory.jsonBuilder().startObject().startObject(type).field("dynamic","strict").startObject("properties");

if (!proNames.isEmpty()){

for (Map.Entry<String, Map<String, String>> proName: proNames.entrySet()) {

if (null != proName.getKey()){

builder.startObject(proName.getKey());

if (!proName.getValue().isEmpty()){

for (Map.Entry<String, String> filed : proName.getValue().entrySet()){

String pro = filed.getKey();

String value = filed.getValue();

if( null != pro && null != value) {

builder.field(pro,value);

}

}
}

builder.endObject();

}

}
}

builder.endObject().endObject().endObject();

String mappingStr=builder.string();

client.admin().indices().prepareCreate(indexName).addMapping(type,mappingStr).setSettings(settings).execute();
}

lrc

赞同来自:

感谢您的帖子,我有两个疑问
1,nested类型,如何通过你的方法进行创建?
2,你的方法参数中的Map结构是怎样的?是否可提供调用范例?
谢谢您的答复!

要回复问题请先登录注册