(从评论中复制的澄清)
我有一个具有不同键值对的java.util.Map
,其中一些值是日期,一些是数字,一些是字符串,还有一些是java.util.Map
,也可以包含上面提到的所有类型。我能够将其放入索引中,我看到elasticsearch映射是使用正确的字段类型自动创建的,现在我希望检索该Map
并查看日期、数字、字符串和嵌套的Map
,而不是我当前拥有的内容-只有字符串和Map
更多的故事:
我使用以下代码在Elasticsearch中放置了一个java.util.Map
:
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 of Maps/List/values。
如何让Java Rest Client遵守Elasticsearch为索引创建的映射?response.getFields()
返回空映射。
如果这是不可能的(比如'source is json/string by design‘等),我已经准备好以最方便的形式检索映射,并自己遍历结果。检索elasticsearch映射的代码将不胜感激。
非常感谢!
发布于 2018-09-20 03:40:26
如果您仍然希望获取类型映射并手动执行转换,Indices API提供了一个可以使用Java Low Level REST Client调用的Get Mapping命令。
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这样的东西来进行数据绑定。将您从Elasticsearch获得的Map
绑定到为文档建模的Java对象,并让Jackson为您处理类型转换。
https://stackoverflow.com/questions/50192035
复制相似问题