Elasticsearch java客户端搜索嵌套字段不工作 [英] Elasticsearch java client search nested field not working
问题描述
我可以使用java api成功创建索引并搜索源字段。我的问题无法使用搜索获取嵌套的关键字段。
I am able to successfully create an index using java api and search the source field. My Problem is not able to get the nested key field using search.
对于我的示例json结构:
For ex my sample json stucture:
{
"name": "John Smith",
"age": 42,
"confirmed": true,
"join_date": "2014-06-01",
"timestamp": "14331222299",
"home": {
"lat": 51.5,
"lon": 0.1
},
"accounts": [
{
"type": "facebook",
"id": "johnsmith"
},
{
"type": "twitter",
"id": "johnsmith"
}
]
}
我可以通过java客户端api将此json作为源代码: -
i can able to index this json as source through java client api:-
IndexResponse response = client.prepareIndex(mohan+"-"+14-10-2014, "mohanelastic")
.setSource(jsonoutput.toString())
.execute()
.actionGet();
我的java客户端搜索api:
My java client search api:
QueryBuilder en = QueryBuilders.matchQuery("name", "John Smith");
FilterBuilder flb = FilterBuilders.andFilter(
FilterBuilders
. .rangeFilter("timestamp").from(starttimeinmilli).to(endtimeinmilli),
FilterBuilders.queryFilter(QueryBuilders.matchQuery("confirmed", "true"))
);
SearchResponse response = client.prepareSearch(mohan+"-"+14-10-2014)
.setTypes("mohanelastic")
.setSearchType(SearchType.QUERY_AND_FETCH)
.setPostFilter(flb)
.setQuery(en)
.setFrom(0).setSize(60)
.execute().actionGet();
在此我可以获得总匹配,关键字段值(名称,年龄,连接日期) 。但是无法获取(home.lat)的键值,它显示空值。任何json的嵌套值都显示为null。
In this i can able to get the total hits, key field values(name,age,join_date). But not able to get the key value for (home.lat) it shows null value. Nested values for any json shows null.
我正在检索源字段json键,并显示相应的值: -
I am retrieving the source field json keys and it shows respective value:-
System.out.println("event type"+response.getHits().getAt(0).getSource().get("name"));
System.out.println("event type"+response.getHits().getAt(0).getSource().get("timestamp"));
但是当我尝试home.lat它显示null值:
But when i try home.lat it shows null value:
System.out.println("event type"+response.getHits().getAt(0).getSource().get("home.lat"));
推荐答案
您无法访问在Java API中使用点符号的home.lat
值。将嵌套对象视为地图( home
)或包含地图(帐户
)的列表。要获得 lat
值,您需要执行以下操作:
You can't access home.lat
value using dot notation in the Java API. Think of nested objects as maps (home
) or a list containing maps (accounts
). To get the lat
value you would need to do the following:
Map<String, Object> source = response.getHits().getAt(0).getSource();
Map<String, Object> home = source.get('home');
Double latValue = (Double) home.get('lat');
这篇关于Elasticsearch java客户端搜索嵌套字段不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!