Created
July 30, 2014 20:27
-
-
Save brankoajzele/eb22ef28443dbadf30d0 to your computer and use it in GitHub Desktop.
elasticsearch-requests-generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if(php_sapi_name() != 'cli' && !empty($_SERVER['REMOTE_ADDR'])) { | |
exit('Only shell execution execution is allowed!'); | |
} | |
$csv = $argv[1]; /* Full absolute path to CSV file */ | |
$_index = $argv[2]; /* Index */ | |
$_type = $argv[3]; /* Index type */ | |
$_id = $argv[4]; /* CSV column to use for ID */ | |
if (file_exists($path=realpath(dirname(__FILE__) . '/'.$csv))) { | |
$csv = $path; | |
} elseif (file_exists($path=realpath($csv))) { | |
$csv = $path; | |
} else { | |
exit('Unable to find CSV file at provided path!'); | |
} | |
$csv_fp = fopen($csv, 'r'); | |
$csv_columns = fgetcsv($csv_fp); | |
if (empty($csv_columns)) { | |
fclose($csv_fp); | |
exit('CSV file does not contain any headers!'); | |
} else { | |
$index_id = array_search($_id, $csv_columns); | |
} | |
$requests = $csv.'.requests.json'; | |
if (file_exists($requests)) { | |
fclose($csv_fp); | |
exit(sprintf('Please remove/rename %s before proceeding!', $requests)); | |
} | |
$requests_fp = fopen($requests, 'w'); | |
while (($entity = fgetcsv($csv_fp)) !== FALSE) { | |
fwrite($requests_fp, sprintf('{ "index" : { "_index" : "%s", "_type" : "%s", "_id" : "%s" } }%s', $_index, $_type, $entity[$index_id], PHP_EOL)); | |
fwrite($requests_fp, json_encode((object)array_combine($csv_columns, $entity)).PHP_EOL); | |
} | |
fclose($requests_fp); | |
fclose($csv_fp); | |
exit('All done...'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment