Skip to content

Instantly share code, notes, and snippets.

@ddpunk
Created November 12, 2013 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddpunk/7429235 to your computer and use it in GitHub Desktop.
Save ddpunk/7429235 to your computer and use it in GitHub Desktop.
class Api::V1::VideosController < Api::V1::ApplicationController
def index
if params[:q] and !params[:q].empty?
client = Elasticsearch::Client.new log: true, hosts: ['http://localhost:9200'], reload_connections: true
# zapytanie DSL
result = client.search index: 'yt', type: 'video', pretty: true,
body: {
query: {
multi_match: {
query: params[:q],
fields: ["title^2", "description", "transcript_en"],
operator: 'or'
}
},
highlight: {
pre_tags: ["<em>"],
post_tags: ["</em>"],
fields: {
'transcript_en.text' => { fragment_size: -1, number_of_fragments: 0, order: 'score' }
}
},
from: params[:offset] || 0,
size: params[:per_page] || 20,
explain: true
}
render json: generate_videos_response(result)
else
render json: {error: 'no query found'}
end
end
private
def generate_videos_response(result)
result = Hashie::Mash.new result
response = Hashie::Mash.new
response.took = result.took
response.timed_out = result.timed_out
response.hits!.total = result.hits.total
response.hits!.max_score = result.hits.max_score
response.videos = []
result.hits.hits.each do |hit|
video = Hashie::Mash.new
video.id = hit._id
video.score = hit._score
video.tags = hit._source.tags
video.title = hit._source.title
video.category = hit._source.category
video.duration = hit._source.duration
video.description = hit._source.description
video.uploaded = hit._source.uploaded
video.updated = hit._source.updated
video.type = hit._source.type
video.url = hit._source.url
video.source!.id = hit._source.source.id
video.source!.type = hit._source.source.type
video.viewCount = hit._source.source.raw['yt$statistics'].viewCount if hit._source.source.raw['yt$statistics']
video.rating = hit._source.source.raw['gd$rating'].average if hit._source.source.raw['gd$rating']
video.thumbnails = {}
hit._source.source.raw['media$group']['media$thumbnail'].each do |thumb|
video.thumbnails['standard-quality'] = thumb.url if thumb['yt$name'] == 'default'
video.thumbnails['high-quality'] = thumb.url if thumb['yt$name'] == 'hqdefault'
video.thumbnails['medium-quality'] = thumb.url if thumb['yt$name'] == 'mqdefault'
end
video.captions = []
if hit.highlight
hit.highlight['transcript_en.text'].each do |text|
hit._source.transcript_en.each do |t|
if text.gsub("<em>","").gsub("</em>","") == t.text
caption = Hashie::Mash.new
caption.language = 'en'
caption.text = t.text
caption.highlight = text
caption.start = t.start
caption.duration = t.dur
video.captions << caption
end
end
end
end
response.videos << video
end
return response
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment