【问题标题】:Delete some specific objects from a JSON file using python and then push the file to Elasticsearch Index使用 python 从 JSON 文件中删除一些特定对象,然后将文件推送到 Elasticsearch Index
【发布时间】:2015-09-21 16:46:15
【问题描述】:

我有一个包含许多对象的大型 json 文件。我试图从这个获取的文件中删除一定数量的对象,因为它们包含公钥和东西.. 只是为了一个参考我有这样的东西命名为 download.json:

"osfamily": "Debian",
"sshrsakey":"Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx2XXX",
"lsbmajdistrelease": "32",
"interfaces": "eth0,lo",
"physicalprocessorcount": 1,
"ec2_kernel_id": "pki-724545-724545",

我的 python 脚本从 SQS 队列中下载上述 json 文件并将其推送到 ES 服务器,如下所示:

import os
import json
import uuid
import time
import boto.sqs
import boto
from boto.sqs.connection import SQSConnection
from boto.sqs.message import Message
from boto.sqs.message import RawMessage

sqs = boto.sqs.connect_to_region("ap-southeast-1")
q = sqs.get_queue("Nishantqueue")

#text_file = open('download.json', 'w')
m = q.read(visibility_timeout=15)
if m == None:
  print "No message!"
else:
  with open('download.json', 'w') as json_data:
    print m.get_body()
    json_data.write(m.get_body())

#    clean_data = json.load(json_data)  ##
#    for element in clean_data:         ##
#      del element['sshdsakey','sshrsakey'] 
#      json_data.write(clean_data) ## 

    json_data.close()
    q.delete_message(m)
    print "Push To ES"
    os.system('./push_to_ES.sh')
    print "Cleaning the temporary json file"
    os.remove('download.json')
    print "++++++ SUCCESSFUL RUN +++++++"

现在您可以在评论部分看到,我正在尝试删除我不想要的对象,然后将其写入 download.json 文件并推送到 ES 。这个评论部分没有按照我的想法工作,并抛出类似:IOError: File not open for reading

任何帮助将不胜感激

【问题讨论】:

    标签: python elasticsearch boto amazon-sqs


    【解决方案1】:

    以读写模式打开文件。

    更改:-

    with open('download.json', 'w') as json_data:

    with open('download.json', 'r+') as json_data:

    -------------编辑------

    为什么不直接做以下事情:-

    clean_data = json.loads(m.get_body())
    for element in clean_data:
      del element['sshdsakey','sshrsakey'] 
    
    #write clean_data to download.json  
    json_data.write(clean_data)
    
    q.delete_message(m)
    print "Push To ES"
    os.system('./push_to_ES.sh')
    print "Cleaning the temporary json file"
    os.remove('download.json')
    print "++++++ SUCCESSFUL RUN +++++++"
    

    【讨论】:

    • 我没有文件“download.json”,我不打算在将其附加到更改文件“read_msg_n_upload_to_ES.py”之前阅读它,第 19 行,在 中open('download.json', 'r+') as json_data: IOError: [Errno 2] No such file or directory: 'download.json'
    • 那么你为什么还要在推送到 ES 之前将数据写入download.json。只需加载m.get_body()中收到的json-->删除不需要的并推送数据。
    • 是的,一个很好的观点......但如果你看到 os.system('./push_to_ES.sh') ,它会调用一个 curl 命令,将 download.json 文件描绘成发送到 ES 进行索引 ...
    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-02
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多