在搜索查询elasticsearch中平坦化json对象



在我的搜索查询中输出如下:

hits" : [
{
"_index" : "77",
"_type" : "_doc",
"_id" : "b5e790c1-5612-42c3-9289-67d5d2d0fdf7",
"_score" : null,
"_source" : {
"[ReferenceNo]" : 12
"[Business Unit]" : {
"[ID]" : 4659,
"RefCode" : "1_qa1",
"Code" : "qa1"
}
}

但是,我希望它像下面这样返回:

hits" : [
{
"_index" : "77",
"_type" : "_doc",
"_id" : "b5e790c1-5612-42c3-9289-67d5d2d0fdf7",
"_score" : null,
"_source" : {
"[ReferenceNo]" : 12
"[Business Unit]" : "qa1"
}
}

对于[Business Unit]字段,我不想返回json对象,而是提取"Code"场。

感谢

在回答这个问题之前,我建议从字段名中删除括号[ ]。请在索引到elasticsearch之前执行此操作,因为在查询elasticsearch时,您将面临许多问题。

您可以使用它的第一个选项,在查询中进行源过滤,如下所示。这很容易,也不会影响性能:

{
"_source": [
"ReferenceNo",
"BusinessUnit.Code"
],
"query": {
"match_all": {}
}
}

以上选项的输出:

{
"_index": "index",
"_id": "us7-8IEBk8SycbzeQ81M",
"_score": 1,
"_source": {
"BusinessUnit": {
"Code": "qa1"
},
"ReferenceNo": 12
}
}

你可以尝试另一个选择是照本宣科,但确保性能:

{
"_source": {
"excludes": "BusinessUnit"
},
"script_fields": {
"b_unit": {
"script": {
"source": "doc['BusinessUnit.Code.keyword']"
}
}
}
}

对上述查询的响应:

{
"_index": "index",
"_id": "us7-8IEBk8SycbzeQ81M",
"_score": 1,
"_source": {
"ReferenceNo": 12
},
"fields": {
"b_unit": [
"qa1"
]
}
}