I have an application in production with ElasticSearch. (It works) but now I can add searchkick gem instead use only elasticsearch.
For this I added the following:
In my Gemfile added:
gem 'elasticsearch-model'
gem 'elasticsearch-rails'
gem 'searchkick'
In my config/initializers/elasticsearch.rb (I'm using Amazon Elasticsearch Service for production. Ok I know this is bad practices but I'll go change this for Environment variables)
if Rails.env == "production"
Elasticsearch::Model.client = Elasticsearch::Client.new url: 'https://xxxxxxxx.xxxxxxx.amazonaws.com/'
else
Elasticsearch::Model.client = Elasticsearch::Client.new url: 'http://localhost:9200/'
end
in models/product.rb
require 'elasticsearch/model'
class Product < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
searchkick
#currently use this function for search. (It works)
scope :searching, ->(query) { __elasticsearch__.search(query).records }
end
but now when I try to use in the server:
Product.search("foobar") #before run: rails c production
Show me the next message: Faraday::ConnectionFailed: Connection refused - connect(2)
After that I try this
rake searchkick:reindex:all RAILS_ENV=production
And I got the same message. Any idea for this ?
After I finished write this post I read this: Searchkick with ElasticSearch returns "Faraday::ConnectionFailed: execution expired"
in config/initializers/elasticsearch.rb
if Rails.env == "production"
url = 'http://myelasticsearch-xyz-foobar.amazonaws.com'
Elasticsearch::Model.client = Elasticsearch::Client.new url: url
Searchkick.client = Elasticsearch::Client.new(hosts: url, retry_on_failure: true, transport_options: {request: {timeout: 250}})
else
url = 'http://localhost:9200/'
Elasticsearch::Model.client = Elasticsearch::Client.new url: url
Searchkick.client = Elasticsearch::Client.new(hosts: url, retry_on_failure: true, transport_options: {request: {timeout: 250}})
end
After refactoring and clean this code I got this:
Elasticsearch::Model.client = Elasticsearch::Client.new url: env['RAILS_ENV']
Searchkick.client = Elasticsearch::Client.new(hosts: env['RAILS_ENV'], retry_on_failure: true, transport_options: {request: {timeout: 250} })
I hope this explanation works for others
I found the above answer to get me 95% of the way there. I followed Nelson's advice and created an Elasticsearch initializer which eliminated the Faraday::ConnectionFailed (Connection refused - connect(2) for "localhost" port 9200):
However I still had to reindex and migrate my Heroku DB.
heroku run rake searchkick:reindex CLASS=YOUR CLASS NAME
then heroku run rake db:migrate
Hope that clarifies for any Heroku newbies such as myself who got stuck on the last part.
If you are using gem 'searchkick' just add the below line in /config/initializers/elasticsearch.rb
ENV["ELASTICSEARCH_URL"] = "http://myelasticsearch-xyz-foobar.amazonaws.com:port"
Related
I'm trying to deploy my sinatra on Heroku https://www.heroku.com/home
I was successful before I tried post method which gave me 404
Get methods work fine:
here is the example of the code:
get '/getPriceList' do //no error, everything works fine
content_type :json, charset: 'utf-8'
today_menu.to_json
end
post '/makeOrder', provides: :json do //error NOT FOUND
data = request.env['rack.input'].read
parsed_data = JSON.parse data.force_encoding('UTF-8')
if User.where(:name => parsed_data['userName']).first.nil?
current = Time.now
fixed = Time.local(current.year, current.month, current.day, 18, 40, 0)
if current > fixed
ObedResponse.new(data, false, 'Vi ne uspeli').to_json
else
#user = User.create(:name => parsed_data['userName'])
#some stuff
end
ObedResponse.new(data, true, "").to_json
end
else
ObedResponse.new(data, false, 'Сегодня вы уже заказали').to_json
end
Can someone tell me why I'm getting this error and how to make the thing work?
PS: I don't have this error while deploying locally using
bundle exec ruby obed.rb -e production
to start
I was in the wrong branch when I commited into Heroku. Changing the branch to master solved the issue.
I am trying to get up and running with bonsai. I intend to use sinatra and ruby (not rails) although right now I am just trying to connect from my local machine. The script is:
require "csv"
require "elasticsearch"
require 'elasticsearch/transport'
Elasticsearch::Model.client = Elasticsearch::Client.new url: 'https://uz09z96il1:5g9p3h8jow#hectors-first-starte-5298580603.us-west-2.bonsai.io', log: true
#Elasticsearch::Client.new host: 'https://uz09z96il1:5g9p3h8jow#hectors-first-starte-5298580603.us-west-2.bonsai.io', log: true
#Elasticsearch::Model.client = Elasticsearch::Client.new('https://uz09z96il1:5g9p3h8jow#hectors-first-starte-5298580603.us-west-2.bonsai.io')
#client = Elasticsearch::Client.new log: true
#Elasticsearch::Model.client = Elasticsearch::Client.new url: 'https://uz09z96il1:5g9p3h8jow#hectors-first-starte-5298580603.us-west-2.bonsai.io', log: true
CSV.open("candidates.csv", "r") do |f|
f.each_with_index do |item, i|
next if i == 0
p item
client.index index: 'data', type: 'person', body: '{
"first": "#{item[1]}",
"last": "#{item[2]}"
}'
end
end
The basic error is that connection is refused, in this particular example like so:
uninitialized constant Elasticsearch::Model (NameError)
As you can see, from the commented out lines, I have tried as many variations as I can think of.
What's the best way to accomplish this? All help gratefully received, thank you.
You are getting
uninitialized constant Elasticsearch::Model (NameError)
because you haven't included the proper class. Try adding:
require 'elasticsearch/model'
At the top of your code.
I have Savon working in a Sinatra ruby application. The application will be called frequently, and I don't want to lean on the server too much.
It looks to me that everytime the /test_savon GET is hit, I am going to the server and asking for the wdsl again. I would only need to do that once, it would seem.
Should I make a few clients as ruby globals (one for each wsdl) and use them repeatedly?
Here is my code which works: NTLM auth - talking to a MS DynamicsNav Server
get '/test_savon' do
# create a client for the service
client = Savon.client(wsdl: 'http://somedynamicsnavserver:7047/WS/Page/Salesperson', ntlm: ["username", "password"]) do
convert_request_keys_to :camelcase
end
operations = client.operations
puts "operations are #{operations.to_s}" if operations
puts "checked operations" if operations
# => [:find_user, :list_users]
# call the 'findUser' operation
response = client.call(:read, message: { code: 'salepersonIDhere' })
puts "response is #{response.to_s}" if response
response.body.to_s
# => {:read_result=>{:salesperson=>{:key=>"aKey", :code=>"salepersonIDhere", :name=>"Jim Kirk", :global_code=>"X", :phone_no=>"4407"}, :#xmlns=>"urn:microsoft-dynamics-schemas/page/salesperson"}}
end
I usually don't use a WSDL at all but work without it. That should be much faster because you should have less roundtrips.
A small example:
#!ruby
gem "savon", "~>2.0"
require 'savon'
stock_handle = ARGV[0] || 'OTEX'
client = Savon.client(
endpoint: 'http://www.webservicex.net/stockquote.asmx',
namespace: 'http://www.webserviceX.NET/',
convert_request_keys_to: :camelcase, # :camelcase, :upcase, :none
log: true,
log_level: :debug,
pretty_print_xml: true
)
response = client.call(
:get_quote,
soap_action: 'http://www.webserviceX.NET/GetQuote',
message: { "wsdl:symbol" => stock_handle}
)
print response.to_hash
I want to use the ruby gem 'twitter' but for an unknown reason it does not work.
Here's the error I get when running the script:
C:/nwcloud/jruby-1.7.2/lib/ruby/gems/shared/gems/faraday-0.8.6/lib/faraday/reques/multipart.rb:5 warning: already initialized constant DEFAULT_BOUNDARY
Twitter::Error::ClientError: initialize: name or service not known
request at C:/nwcloud/jruby-1.7.2/lib/ruby/gems/shared/gems/twitter-4.5.0/lib/twitter/client.rb:85
get at C:/nwcloud/jruby-1.7.2/lib/ruby/gems/shared/gems/twitter-4.5.0/lib/twitter/client.rb:64
__send__ at org/jruby/RubyBasicObject.java:1671
send at org/jruby/RubyKernel.java:2094
cursor_from_response at C:/nwcloud/jruby-1.7.2/lib/ruby/gems/shared/gems/twitter-4.5.0/lib/twitter/api/utils.rb:108
cursor_from_response_with_user at C:/nwcloud/jruby-1.7.2/lib/ruby/gems/shared/gems/twitter-4.5.0/lib/twitter/api/utils.rb:96
friends at C:/nwcloud/jruby-1.7.2/lib/ruby/gems/shared/gems/twitter-4.5.0/lib/twitter/api/friends_and_followers.rb:314
(root) at tCon.rb:11
I registered my application in my twitter developer account and installed the gem.
Here's my coding (I removed all keys):
require 'twitter'
client = Twitter::Client.new(
:consumer_key => "",
:consumer_secret => "",
:oauth_token => "",
:oauth_token_secret => ""
)
client.update("I'm tweeting with #gem!")`
I also tried just to do it like this:
Twitter.configure do |config|
config.consumer_key = YOUR_CONSUMER_KEY
config.consumer_secret = YOUR_CONSUMER_SECRET
config.oauth_token = YOUR_OAUTH_TOKEN
config.oauth_token_secret = YOUR_OAUTH_TOKEN_SECRET
end
.. it doesn't work :-( .. I'm a newbie to ruby so perhaps I forgot sth...
I'm really looking forward to your answers. Thank you in advance!!!
I think it was a proxy problem. After deploying it to the cloud it worked!
I am attempting to use redis store as my session store on heroku. It works fine in development but I am unable to get a redis connection on heroku. It is attempting to connect to a 127.0.0.1 instead of the correct redis server.
Error:
ActionView::Template::Error (Error connecting to Redis on 127.0.0.1:6379 (ECONNREFUSED)):
I have set the heroku redis config to the correct server (not really using for the session store but it is set)
REDISTOGO_URL: redis://redistogo:#################################carp.redistogo.com:9274/
session_store.rb
GrnAuth::Application.config.session_store :redis_store, :server => APP_CONFIG['redis_server'], key: '_grn_session'
environment.rb
# Load the rails application
require File.expand_path('../application', __FILE__)
require 'yaml'
APP_CONFIG = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]
# Initialize the rails application
GrnAuth::Application.initialize!
config.yml
development:
redis_server: redis://localhost:6379/
test:
redis_server: redis://localhost:6379/
production:
redis_server: redis://redistogo:#################################carp.redistogo.com:9274/
When I console in to heroku I can check APP_CONFIG['redis_server'] and it is set to the redis server.
I have also set up a redis connection just to use that works.
redis.rb
uri = URI.parse(ENV["REDISTOGO_URL"] || "redis://localhost:6379/" )
$redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
When I console in to heroku I can do and get the following
irb(main):001:0> $redis
=> #<Redis client v3.0.1 for redis://carp.redistogo.com:9274/0>
Any help would be much appreciated. Thank you.
It looks like this:
GrnAuth::Application.config.session_store :redis_store, :server => APP_CONFIG['redis_server'], key: '_grn_session'
Should instead be this:
GrnAuth::Application.config.session_store :redis_store, :servers => APP_CONFIG['redis_server'], key: '_grn_session'