繁体   English   中英

如何使用Java手动展平Elasticsearch嵌套JSON文档?

[英]How to manually flatten Elasticsearch nested JSON documents using Java?

我想为我的Elasticsearch文档结构生成一些文档。 问题是我将嵌套的JSON存储在索引中,但是我想记录一下Elasticsearch生成的扁平化JSON格式¹。

是否有一种类似于Elasticsearch使用ES Java API生成的方式来扁平化JSON的方法?

如果可能的话,我不想为此任务启动Elasticsearch。

JSON示例:

{
  "title": "Nest eggs",
  "body":  "Making your money work...",
  "tags":  [ "cash", "shares" ],
  "comments": [ 
    {
      "name":    "John Smith",
      "comment": "Great article",
      "age":     28,
      "stars":   4,
      "date":    "2014-09-01"
    },
    {
      "name":    "Alice White",
      "comment": "More like this please",
      "age":     31,
      "stars":   5,
      "date":    "2014-10-22"
    }
  ]
}

Elasticsearch将其展平后,该文档将看起来像这样。

{
  "title":            [ eggs, nest ],
  "body":             [ making, money, work, your ],
  "tags":             [ cash, shares ],
  "comments.name":    [ alice, john, smith, white ],
  "comments.comment": [ article, great, like, more, please, this ],
  "comments.age":     [ 28, 31 ],
  "comments.stars":   [ 4, 5 ],
  "comments.date":    [ 2014-09-01, 2014-10-22 ]
}

[1] https://www.elastic.co/guide/zh-CN/elasticsearch/guide/current/nested-objects.html

我写了我自己的算法,该算法展平了用于创建JSON的Map。

private void flatten(Map<String, Object> map, Map<String, Object> output, String key) throws JSONException {
        String prefix = "";
        if (key != null) {
            prefix = key + ".";
        }
        for (Entry<String, Object> entry : map.entrySet()) {
            String currentKey = prefix + entry.getKey();
            if (entry.getValue() instanceof Map) {
                flatten((Map<String, Object>) entry.getValue(), output, prefix + entry.getKey());
            } else if (entry.getValue() instanceof List) {
                output.put(currentKey, entry.getValue());
            } else {
                output.put(currentKey, entry.getValue());
            }
        }
    }

用法示例:

    Map<String, Object> outputMap = new TreeMap<>();
    flatten(inputMap, outputMap, null);
    JSONObject json = new JSONObject(outputMap);
    String jsonStr = json.toString(4);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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