Files
old-ribica/front-api/controllers/search.rb

46 lines
1.1 KiB
Ruby
Raw Normal View History

2015-03-22 16:16:52 +01:00
get '/search' do
2015-10-11 06:37:17 +02:00
results = { }
begin
es_client = Elasticsearch::Client.new log: true
q = params[:q]
# for now we do the basic query
results = es_client.search index: 'ribica', type: 'items', body: { query: { match: { _all: q } } }
rescue Exception => error
puts error.inspect
results = { "hits" => {"hits" => [ {"_id" => Item.first.id, "_score" => 2 }, {"_id" => Item.last.id, "_score" => 1 } ]}}
end
ids = results["hits"]["hits"].map do |r|
r["_id"]
2015-03-22 16:16:52 +01:00
end
ids_with_score = {}
results["hits"]["hits"].each do |r|
2015-10-11 06:37:17 +02:00
ids_with_score[r["_id"].to_i] = {:score => r["_score"], :item => nil}
2015-03-22 16:16:52 +01:00
end
2015-10-11 06:37:17 +02:00
2015-03-22 16:16:52 +01:00
if ids.length > 0
2015-10-11 06:37:17 +02:00
res = Item.where(:id => ids).to_a
# make sure we have correct relevance order, since `where in` does not guarantee order
res.each do |ii|
ids_with_score[ii.id][:item] = ii
end
final = []
ids_with_score.each do |k,v|
final << v
end
final.sort_by! {|v| -v[:score]}
final = final.map do |f|
f[:item]
end
prepare_items_for_mass_display(final)
2015-03-22 16:16:52 +01:00
else
2015-10-11 06:37:17 +02:00
[].to_json
2015-03-22 16:16:52 +01:00
end
end