How to insert a single json string into elasticsearch with a ruby script

Viewed 382

First i want to mention that i am very new working with both Elasticsearch and Ruby, but my new part time job requires me to do this.

I am looking for a way to insert a string from my ruby file, that is in json format, into my elasticsearch. the Json string looks like this

{
"key" : "dummykey1",
"properbility" : 2,
"severity" : 3,
"summary" : "this is a dummy summary"
}

(this is just dummy data for testing atm)

and my elasticsearch post url is "http://localhost:9200/jira_issues3/_doc/1"

using postman to insert this works perfectly, but i need a way to do it in a ruby script and i have no idea where to start.

i have a hard time finding anything on google, because when i search for both ruby and elasticsearch, all that comes up is how to install elasticsearch on your ruby on rails project. I am sorry if this is a stupid question, but i feel like i am out of options.

for anyone who tries to help my stupid brain, thank you very much <3

1 Answers

If you only need to index some JSON content into your cluster, you can do it with plain Ruby and net/http:

# Plain Ruby:
require 'net/http'

json = <<-JSON
{
  "key" : "dummykey1",
  "properbility" : 2,
  "severity" : 3,
  "summary" : "this is a dummy summary"
}
JSON

uri = URI('http://localhost:9200/jira_issues3/_doc/9')
response = Net::HTTP.post uri, json, "Content-Type" => "application/json"
puts response

If you're going to interact with the Elasticsearch cluster from your Ruby app, I'd suggest taking a look at the official Elasticsearch Ruby client.

# With the Elasticsearch client:
require 'elasticsearch'
client = Elasticsearch::Client.new
response = client.index(index: 'jira_issues3', body: json, id: 1)
puts response

There's two different gems to work with Elasticsearch on your Ruby projects:

The first gem is the official client for Elasticsearch. It provides full API support and many other features. The second one is Rails Integrations for Elasticsearch, which depends on the first and may have way more stuff than you actually need.

Related