46 lines
1.1 KiB
Ruby
46 lines
1.1 KiB
Ruby
get '/search' do
|
|
|
|
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"]
|
|
end
|
|
|
|
ids_with_score = {}
|
|
results["hits"]["hits"].each do |r|
|
|
ids_with_score[r["_id"].to_i] = {:score => r["_score"], :item => nil}
|
|
end
|
|
|
|
|
|
if ids.length > 0
|
|
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)
|
|
else
|
|
[].to_json
|
|
end
|
|
end
|