1

我有一个 elasticsearch 集群,我正在对多个索引(msearch)进行搜索,它返回一个对象数组(每个被查询的索引一个对象)。这些对象中的每一个在 hits 对象中都有一个命中数组。我真的只在 _source 对象之后。您将如何获取所有嵌套的“_source”对象的数组?

[
  {
    "hits": {
      "hits": [
        {
          "_index": "index1",
          "_type": "type1",
          "_id": "1",
          "_score": 12.163426,
          "_source": {
            "somekey": "some value",
            "someotherkey": "another value"
          }
        }
      ]
    },
  },
  {
    "hits": {
      "hits": []
    },
  },
  {
    "hits": {
      "hits": [
        {
          "_index": "index2",
          "_type": "type2",
          "_id": "2",
          "_score": 7.0380797,
          "_source": {
            "somekey": "some value",
            "someotherkey": "another value"
          }
        },
        {
          "_index": "index2",
          "_type": "type2",
          "_id": "3",
          "_score": 6.07253,
          "_source": {
            "somekey": "some value 2",
            "someotherkey": "another value 2"
          }
        }
      ]
    },
  },
]
4

2 回答 2

2

您可以使用Array.prototype.flatMap()来遍历您的外部数组并将属性数组转换Array.prototype.map()为项目:hits.hits_source

const src = [{"hits":{"hits":[{"_index":"index1","_type":"type1","_id":"1","_score":12.163426,"_source":{"somekey":"some value","someotherkey":"another value"}}]},},{"hits":{"hits":[]},},{"hits":{"hits":[{"_index":"index2","_type":"type2","_id":"2","_score":7.0380797,"_source":{"somekey":"some value1","someotherkey":"another value1"}},{"_index":"index2","_type":"type2","_id":"3","_score":6.07253,"_source":{"somekey":"some value 2","someotherkey":"another value 2"}}]},},],

result = src.flatMap(o => o.hits.hits.map(({_source}) => _source))

console.log(result)
.as-console-wrapper{min-height:100%;}

于 2020-07-30T21:30:51.937 回答
0

您可以减少对象:

const src = [
  {
    "hits": {
      "hits": [
        {
          "_index": "index1",
          "_type": "type1",
          "_id": "1",
          "_score": 12.163426,
          "_source": {
            "somekey": "some value",
            "someotherkey": "another value"
          }
        }
      ]
    },
  },
  {
    "hits": {
      "hits": []
    },
  },
  {
    "hits": {
      "hits": [
        {
          "_index": "index2",
          "_type": "type2",
          "_id": "2",
          "_score": 7.0380797,
          "_source": {
            "somekey": "some value",
            "someotherkey": "another value"
          }
        },
        {
          "_index": "index2",
          "_type": "type2",
          "_id": "3",
          "_score": 6.07253,
          "_source": {
            "somekey": "some value 2",
            "someotherkey": "another value 2"
          }
        }
      ]
    },
  },
];
console.log(src.reduce((prev, el) => [...prev, ...el.hits.hits.map(o => o['_source'])], []))

于 2020-07-30T21:30:51.610 回答