简体   繁体   中英

Get the types (String, Boolean , Int, Nested etc ) of each field in the mapping with Java API

I want to get the types of all my fields in my mapping with java API.

With this I can retrieve all the fields:

ClusterState cs = Client.admin().cluster().prepareState().execute().actionGet().getState();
IndexMetaData imd = cs.getMetaData().index(customerName);
MappingMetaData mmd = imd.mapping(type);
Map<String, Object> source = mmd.sourceAsMap();
for (String i : source.keySet()) {
        JSONObject jsonSource = null;
            try {
                jsonSource = new JSONObject(source.get(i).toString());
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Iterator<?> iterator = jsonSource.keys();
            while (iterator.hasNext()) {
                listFields.add(iterator.next().toString());
            }

        }

I looked for the methods in MappingMetaData but I got nothing that can give me the types of the field (eg: string, float, int etc). I need to reatrive in the list of field only the ones which are core types (not with nested or inner object )

You can use Jackson's JsonNode:

MappingMetaData mmd = imd.mapping(type);
CompressedString source = mmd.source();
JsonNode mappingNode = new ObjectMapper().readTree(source));

JsonNode propertiesNode = mappingNode.get("properties");
Iterator<Entry<String, JsonNode>> properties = propertiesNode.fields();
while (properties.hasNext()) {

  Entry<String, JsonNode> node = properties.next();
  String name = node.getKey();
  JsonNode valueNode = node.getValue();
  if (valueNode != null) {
    String type = valueNode.get("type").asText();//gives you the type
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM