数据为:
{
"_index": "data_collection",
"_type": "doc",
"_id": "AXc3PJHBel1m6pmwJ9YF",
"_score": 0,
"_source": {
"create_time": "2021-01-25T01:50:52.352Z",
"data_collection_name": "gl_jcdl",
"data_source_id": "AXc3PJC1el1m6pmwJ9YE",
"delete_class": "0",
"project_id": "AXcjKFMAel1m6pmwJ9D6",
"sub_collections": [
{
"data_task_id": "aximakraqhzinkg8kzwj",
"dataClassification": "基础",
"geo_level": null,
"index_library_name": "AXcjKFIyel1m6pmwJ9D4",
"layerName": "aaa",
"sub_collection_name": "aaa_20",
"table_name": "axif3xroqhzinkg8kncc"
},
{
"data_task_id": "AXiF4AQcQHzinkG8KNNR",
"dataClassification": "基础",
"geo_level": null,
"index_library_name": "AXcjKFIyel1m6pmwJ9D4",
"layerName": "bbb",
"sub_collection_name": "aaa_21",
"table_name": "axif4agcqhzinkg8knno"
}
],
"update_time": "2021-01-25T01:50:52.352Z"
}
查询结果为:
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0,
"hits": [
{
"_index": "data_collection",
"_type": "doc",
"_id": "AXc3PJHBel1m6pmwJ9YF",
"_score": 0,
"_source": {},
"inner_hits": {
"sub_collections": {
"hits": {
"total": 1,
"max_score": 3.9665112,
"hits": [
{
"_nested": {
"field": "sub_collections",
"offset": 10
},
"_score": 3.9665112,
"_source": {
"data_task_id": "aximakraqhzinkg8kzwj",
"dataClassification": "基础",
"geo_level": null,
"index_library_name": "AXcjKFIyel1m6pmwJ9D4",
"layerName": "aaa",
"sub_collection_name": "aaa_20",
"table_name": "axif3xroqhzinkg8kncc"
}
}
]
}
}
}
}
]
}
}
首先使用nestedQuery,按条件sub_collections.table_name查询子对象,
再使用inner_hits可以获取到,对象数组中符合查询条件的值
其中xx为需要获取的返回数据字段
SearchResponse response = client.prepareSearch("data_collection")
.setQuery(QueryBuilders.nestedQuery("sub_collections",
QueryBuilders.termsQuery("sub_collections.table_name", tableNames),
ScoreMode.None).innerHit(new InnerHitBuilder()
.setSize(Constant.MAX_ES_SEARCH_NUM)
))
.setFetchSource(new String[]{"xx"},null)
.execute()
.actionGet();
构建后的查询语句为
{
"query": {
"nested": {
"query": {
"terms": {
"sub_collections.table_name": [
"aximakraqhzinkg8kzwj"
],
"boost": 1
}
},
"path": "sub_collections",
"ignore_unmapped": false,
"score_mode": "none",
"boost": 1,
"inner_hits": {
"ignore_unmapped": false,
"from": 0,
"size": 1000,
"version": false,
"explain": false,
"track_scores": false
}
}
},
"_source": {
"includes": ["aa"]
}
}