-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv2opensearch.rb
executable file
·86 lines (62 loc) · 1.74 KB
/
csv2opensearch.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/ruby
require 'csv'
require 'json'
require 'opensearch'
# I could have done more.
# Not the greatest ruby code.
# Must stop repeating.
# This just happens to be the index mapping I want to use. Replace this with your mapping.
# TODO: Make it take a mapping via a json file.
indexMapping = {
'mappings': {
'properties': {
'created_at': { "type": "date",
"format": "yyyy-MM-dd HH:mm:ss zzz" },
'tag': { "type": "keyword" },
'category_id': { "type": "keyword" },
'title': { "type": "keyword" }
}
}
}
def usage
puts "Usage: #{__FILE__} <index_name> <input_csv_file>"
exit
end
def createIndex(name, mapping)
puts "Creating index #{name}."
@client.indices.create(
index: name,
body: mapping
)
end
def indexExists(indexName)
@client.indices.exists(
index: indexName,
)
end
def indexData(fileName, index)
csvFile = File.open(fileName, "r")
csvData = csvFile.read()
csv = CSV.new(csvData, :headers => true, :header_converters => :symbol, :converters => :all)
csvData = csv.to_a.map {|row| row.to_hash }
csvData.each do |csvRow|
response = @client.index(
index: index,
body: csvRow,
refresh: true
)
puts response
end
end
begin
@user = ENV['OS_USER'] || "admin"
@password = ENV['OS_PASSWORD'] || "admin"
@client = OpenSearch::Client.new( host: "https://#{@user}:#{@password}@localhost:9200/", transport_options: { ssl: { verify: false } })
rescue StandardError => e
puts "Something bad happened creating the OpenSearch client object."
end
usage if ARGV.length < 2
indexName = ARGV[0]
createIndex(indexName, indexMapping) unless indexExists(indexName)
fileName = ARGV[1]
indexData(fileName, indexName)