feat: now use batches but seem to write less rows, not sure
This commit is contained in:
110
new_write.py
110
new_write.py
@@ -26,6 +26,10 @@ json_files = glob.glob('./sec_data/companyfacts/*.json')
|
|||||||
file_count = len(json_files)
|
file_count = len(json_files)
|
||||||
current_file = 1
|
current_file = 1
|
||||||
|
|
||||||
|
# Batch size configuration - process `batch_size` files at a time
|
||||||
|
batch_size = 50 # Adjust this number to your preference or based on system resources
|
||||||
|
rows = []
|
||||||
|
|
||||||
# Data type mapping for the DataFrame to SQL conversion
|
# Data type mapping for the DataFrame to SQL conversion
|
||||||
dtype_map = {
|
dtype_map = {
|
||||||
'entity_cik': Integer,
|
'entity_cik': Integer,
|
||||||
@@ -46,69 +50,71 @@ dtype_map = {
|
|||||||
'frame': String(255)
|
'frame': String(255)
|
||||||
}
|
}
|
||||||
|
|
||||||
for json_file in json_files:
|
# Iterate through the JSON files in batches
|
||||||
try:
|
for i in range(0, file_count, batch_size):
|
||||||
# Load the JSON data
|
batch_files = json_files[i:i+batch_size]
|
||||||
with open(json_file) as f:
|
|
||||||
data = json.load(f)
|
|
||||||
|
|
||||||
# Informing the user about the current file being processed
|
for json_file in batch_files:
|
||||||
print(f"Processing file {current_file}/{file_count}: {json_file}")
|
try:
|
||||||
current_file += 1
|
# Load the JSON data
|
||||||
|
with open(json_file) as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
# Check if the JSON has the keys we're interested in
|
# Informing the user about the current file being processed
|
||||||
cik = data.get('cik', None)
|
print(f"Processing file {current_file}/{file_count}: {json_file}")
|
||||||
entity_name = data.get('entityName', None)
|
current_file += 1
|
||||||
facts = data.get('facts', {})
|
|
||||||
|
|
||||||
# Initialize a list to hold rows
|
# Check if the JSON has the keys we're interested in
|
||||||
rows = []
|
cik = data.get('cik', None)
|
||||||
|
entity_name = data.get('entityName', None)
|
||||||
|
facts = data.get('facts', {})
|
||||||
|
|
||||||
# Skip files that don't have facts to process
|
# Skip files that don't have facts to process
|
||||||
if not facts:
|
if not facts:
|
||||||
print(f"File {json_file} has no facts to process. Skipping...")
|
print(f"File {json_file} has no facts to process. Skipping...")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Process the facts dynamically
|
# Process the facts dynamically
|
||||||
for taxonomy, fact_items in facts.items():
|
for taxonomy, fact_items in facts.items():
|
||||||
for fact_id, fact_data in fact_items.items():
|
for fact_id, fact_data in fact_items.items():
|
||||||
label = fact_data.get('label', None)
|
label = fact_data.get('label', None)
|
||||||
description = fact_data.get('description', None)
|
description = fact_data.get('description', None)
|
||||||
units = fact_data.get('units', {})
|
units = fact_data.get('units', {})
|
||||||
|
|
||||||
for unit, details_list in units.items():
|
for unit, details_list in units.items():
|
||||||
for details in details_list:
|
for details in details_list:
|
||||||
# Generate row dictionary dynamically, only updating non-None values
|
# Generate row dictionary dynamically, only updating non-None values
|
||||||
row = {
|
row = {
|
||||||
'entity_cik': cik,
|
'entity_cik': cik,
|
||||||
'entity_name': entity_name,
|
'entity_name': entity_name,
|
||||||
'fact_id': fact_id,
|
'fact_id': fact_id,
|
||||||
'fact_taxonomy': taxonomy,
|
'fact_taxonomy': taxonomy,
|
||||||
'fact_label': label,
|
'fact_label': label,
|
||||||
'fact_description': description,
|
'fact_description': description,
|
||||||
'fact_unit': unit
|
'fact_unit': unit
|
||||||
}
|
}
|
||||||
|
|
||||||
# Add the remaining keys in details to row
|
# Add the remaining keys in details to row
|
||||||
for key, value in details.items():
|
for key, value in details.items():
|
||||||
row[key] = value
|
row[key] = value
|
||||||
|
|
||||||
# Append the row to rows list
|
# Append the row to rows list
|
||||||
rows.append(row)
|
rows.append(row)
|
||||||
|
|
||||||
# Create DataFrame only if there are rows
|
except json.JSONDecodeError as e:
|
||||||
if rows:
|
print(f"Failed to process file {json_file}: Invalid JSON format. Error: {e}")
|
||||||
df = pd.DataFrame(rows)
|
|
||||||
|
|
||||||
# Write DataFrame to the 'data' table, appending if table exists
|
except Exception as e:
|
||||||
df.to_sql('data', con=engine, if_exists='append', index=False, dtype=dtype_map)
|
print(f"An error occurred while processing file {json_file}: {e}")
|
||||||
else:
|
|
||||||
print(f"No data rows were created for file {json_file}. Skipping insert...")
|
|
||||||
|
|
||||||
except json.JSONDecodeError as e:
|
# After processing batch_files, insert accumulated rows into the database
|
||||||
print(f"Failed to process file {json_file}: Invalid JSON format. Error: {e}")
|
if rows:
|
||||||
|
df = pd.DataFrame(rows)
|
||||||
|
|
||||||
except Exception as e:
|
# Write DataFrame to the 'data' table, appending if table exists
|
||||||
print(f"An error occurred while processing file {json_file}: {e}")
|
df.to_sql('data', con=engine, if_exists='append', index=False, dtype=dtype_map)
|
||||||
|
|
||||||
|
# Clear the list of rows for the next batch
|
||||||
|
rows.clear()
|
||||||
|
|
||||||
print("Processing complete. All files have been handled.")
|
print("Processing complete. All files have been handled.")
|
||||||
Reference in New Issue
Block a user