![](/img/trans.png)
[英]How to map the resultset of elasticsearch query with Java High Level Rest Client API?
[英]Elasticsearch High Level Rest Client - java Map with typed (sub) fields - dates, numbers etc
(從評論中復制的澄清)
我有一個java.util.Map
,它有不同的鍵值對,一些值是日期,一些數字,一些是字符串,還有一些也是java.util.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對象,因為我只有地圖/列表/值的地圖。
如何使Java Rest Client尊重Elasticsearch為索引創建的映射? response.getFields()
返回空映射。
如果不可能(比如'source is json / strings by design'等),我准備以最方便的形式檢索映射,並自己遍歷結果。 檢索彈性搜索映射的代碼將不勝感激。
非常感謝!
如果您仍想獲取類型映射並手動執行轉換,則Indices API具有可以使用Java低級REST客戶端調用的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為您處理類型轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.