我需要从大量 JSON 数组中检索特定索引处的对象。该数组包含 2,000,000 个对象,文件大小约为 5GB。
我已经尝试了将
jq
与 Python 结合使用的各种方法,但性能仍然是一个问题。
以下是我尝试过的一些方法:
直接索引:
jq -c '.[100000]' Movies.json
吸食和索引:
jq --slurp '.[0].[100000]' Movies.json
使用
nth()
:
jq -c 'nth(100000; .[])' Movies.json
虽然这些方法似乎有效,但对于我的要求来说太慢了。我还尝试过使用流,这显着提高了性能:
jq -cn --stream 'nth(100000; fromstream(1|truncate_stream(inputs)))' Movies.json
但是,随着索引的增加,检索时间也会增加,我怀疑这是由于流式传输的运行方式所致。
我知道一种选择是将文件分成块,但我宁愿避免通过这样做创建额外的文件。
JSON结构示例:
[
{
"Item": {
"Name": "Darkest Legend",
"Year": 1992,
"Genre": ["War"],
"Director": "Sherill Eal Eisenberg",
"Producer": "Arabella Orth",
"Screenplay": ["Octavia Delmer"],
"Cast": ["Johanna Azar", "..."],
"Runtime": 161,
"Rate": "9.0",
"Description": "Robin Northrop Cymbre",
"Reviews": "Gisela Seumas"
},
"Similars": [
{
"Name": "Smooth of Edge",
"Year": 1985,
"Genre": ["Western"],
"Director": "Vitoria Eustacia",
"Producer": "Auguste Jamaal Corry",
"Screenplay": ["Jaquenette Lance Gibe"],
"Cast": ["Althea Nicole", "..."],
"Runtime": 96,
"Rate": "6.5",
"Description": "Ashlan Grobe",
"Reviews": "Annnora Vasquez"
}
]
},
...
]
如何提高从这么大的数组中检索对象的效率?
不是经过测试的解决方案(由于缺少数据),但我认为表达式
nth(100000; fromstream(1|truncate_stream(inputs)))
创建 100000 个对象并将它们扔掉(除了最后一个)。
这个表达式应该避免这种开销并且可能会更快:
fromstream(1|truncate_stream( inputs | select(.[0][0] == 100000)))