我想为我的 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 的 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);
关于java - 如何使用 Java 手动展平 Elasticsearch 嵌套的 JSON 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32092170/