(从评论中复制的澄清)
我有一个java.util.Map
,它有不同的键值对,有些值是日期,有些是数字,有些是字符串,有些也是java.util .Map
s 也可以包含上述各种类型。我能够将它放入索引中,我看到 Elasticsearch 映射是使用正确的字段类型自动创建的,现在我想检索该 Map
并查看日期、数字、字符串和嵌套 Map
s 而不是我目前拥有的 - 只是字符串和 Maps
进一步的故事:
我使用以下代码将 java.util.Map
放入 Elasticsearch:
public void putMap(String key, Map<String, ?> value) {
try {
IndexRequest ir = Requests.indexRequest(_index)
.id(key)
.type("doc")
.source(value);
Factory.DB.index(ir); // the high level rest client here
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
我无法根据我的任务明确创建映射。
对于我的一个索引,它创建了这样的映射,这很好:
{
"rex": {
"mappings": {
"doc": {
"properties": {
"variables": {
"properties": {
"customer": {
"properties": {
"accounts": {
"properties": {
"dateOpen": {
"type": "date"
},
"id": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"dateOfBirth": {
"type": "date"
},
"firstName": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"id": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"lastName": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"middleName": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
}
}
}
}
}
现在我正在使用以下代码检索我的结构,
public Map<String, ?> getMap(String key) {
try {
GetRequest gr = new GetRequest(_index, "doc", key);
try {
GetResponse response = Factory.DB.get(gr);
if (!response.isExists()) {
return null;
}
Map<String, ?> ret = response.getSourceAsMap();
return ret;
} catch (ElasticsearchStatusException ee) {
if (ee.status().getStatus() == RestStatus.NOT_FOUND.getStatus()) {
return null;
} else {
throw new RuntimeException(ee);
}
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
日期以字符串形式返回,例如“1957-04-29T00:00:00.000Z”
没有可将此文档映射到的 Java 对象,因为我只有 Maps/Lists/values 的 Maps。
如何让 Java Rest Client 尊重 Elasticsearch 为索引创建的映射? response.getFields()
返回空 map 。
如果不可能(例如“源是 json/strings by design”等),我准备以最方便的形式检索映射,并自己浏览结果。检索 Elasticsearch 映射的代码将不胜感激。
非常感谢!
最佳答案
如果您仍想获取类型映射并手动进行转换,Indices API 有一个 Get Mapping您可以使用 Java Low Level REST Client 调用的命令.
String getMapping(RestHighLevelClient client, String index, String type) throws IOException {
String endpoint = index + "/_mapping/" + type;
Response response = client.getLowLevelClient().performRequest("GET", endpoint);
return EntityUtils.toString(response.getEntity());
}
但实际上,我建议您改用 Jackson 之类的东西进行数据绑定(bind)。将您从 Elasticsearch 获得的 Map
绑定(bind)到为文档建模的 Java 对象,让 Jackson 为您处理类型转换。
关于java - Elasticsearch High Level Rest Client - 带有类型(子)字段的 Java map - 日期、数字等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50192035/