fed*_*edd 11 java elasticsearch
(从评论中复制的澄清)
我有一个java.util.Map具有不同键值对,并且一些值是日期,一些数字,一些是字符串,还有一些也java.util.Map可以包含所有类型的上述类型.我能够将它放入索引中,我看到弹性搜索映射是使用正确的字段类型自动创建的,现在我想检索它Map并查看日期,数字,字符串和嵌套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);
}
}
Run Code Online (Sandbox Code Playgroud)
我无法根据我的任务明确创建映射.
对于我的一个索引,它创建了这样的映射,这很好:
{
"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
}
}
}
}
}
}
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我用以下代码检索我的结构,
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);
}
}
Run Code Online (Sandbox Code Playgroud)
日期以字符串形式返回,如"1957-04-29T00:00:00.000Z"
没有用于映射此文档的Java对象,因为我只有地图/列表/值的地图.
如何使Java Rest Client尊重Elasticsearch为索引创建的映射?response.getFields()返回空地图.
如果不可能(比如'source is json/strings by design'等),我准备以最方便的形式检索映射,并自己遍历结果.检索弹性搜索映射的代码将不胜感激.
非常感谢!
如果您仍然想获取类型映射并手动进行转换,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());
}
Run Code Online (Sandbox Code Playgroud)
但实际上我建议使用 Jackson 之类的东西进行数据绑定。将Map您从 Elasticsearch 获得的数据绑定到对文档进行建模的 Java 对象,并让 Jackson 为您处理类型转换。
| 归档时间: |
|
| 查看次数: |
1180 次 |
| 最近记录: |