如何使用 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/en/elasticsearch/guide/current/nested-objects.html

我编写了我自己的算法来展平将用于创建 JSON 的地图。

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);