Created
May 12, 2015 23:28
-
-
Save pnicholls/ae9ecc5332754d8c909d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Stock < ActiveRecord::Base | |
include Elasticsearch::Model | |
include Elasticsearch::Model::Callbacks | |
belongs_to :exchange | |
belongs_to :company | |
has_many :comments, as: :commentable | |
has_many :tasks | |
has_many :task_comments, through: :tasks, source: :comments | |
def search_tokens | |
tokens = [] | |
tokens << symbol | |
tokens << company.name | |
end | |
__elasticsearch__.client = Elasticsearch::Client.new url: ENV['BONSAI_URL'], log: true | |
settings :index => { :number_of_shards => 1 } do | |
mappings :dynamic => 'false' do | |
indexes :symbol, :type => 'string' | |
indexes :symbol_suggest, :type => 'completion', :index_analyzer => 'simple', :search_analyzer => 'simple', :payloads => true | |
indexes :company_name, :type => 'string' | |
indexes :company_name_suggest, :type => 'completion', :index_analyzer => 'simple', :search_analyzer => 'simple', :payloads => true | |
end | |
end | |
def self.suggest(query) | |
response = Stock.__elasticsearch__.client.suggest(:index => Stock.index_name, :body => { | |
:suggestions => { | |
:text => query, | |
:completion => { | |
:field => 'suggest' | |
} | |
} | |
}) | |
response["suggestions"].first["options"] | |
end | |
def as_indexed_json(options={}) | |
{ | |
:name => self.symbol, | |
:suggest => { | |
:input => [self.symbol, self.company.name], | |
:output => self.symbol, | |
:payload => { | |
:id => self.id, | |
:symbol => self.symbol, | |
:company => self.company.name, | |
:exchange => self.exchange.symbol, | |
:value => "#{self.symbol} #{self.company.name} #{self.exchange.symbol}" | |
} | |
} | |
}.as_json() | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment