[Search] fix Elasticsearch podcast query
[mygpo.git] / mygpo / search / index.py
blob1a91a777d4e1ffc5f373e1706161f2282e41864b
2 """ Contains code for indexing other objects """
4 from pyes import ES, QueryStringQuery, FunctionScoreQuery
5 from pyes.exceptions import IndexAlreadyExistsException, NoServerAvailable
7 from django.conf import settings
9 from mygpo.search.json import podcast_to_json
10 from mygpo.search.models import PodcastResult
12 import logging
13 logger = logging.getLogger(__name__)
16 def get_connection():
17 """ Create a connection from Django settings """
18 conn = ES([settings.ELASTICSEARCH_SERVER],
19 timeout=settings.ELASTICSEARCH_TIMEOUT)
20 return conn
23 def index_podcast(sender, **kwargs):
24 """ Indexes a podcast """
26 conn = get_connection()
27 podcast = kwargs['instance']
28 logger.info('Indexing podcast %s', podcast)
30 document = podcast_to_json(podcast)
32 try:
33 conn.index(document, settings.ELASTICSEARCH_INDEX,
34 'podcast', podcast.id.hex)
35 except NoServerAvailable:
36 logger.exception('Indexing podcast failed')
39 def create_index():
40 """ Creates the Elasticsearch index """
41 conn = get_connection()
43 logger.info('Creating index %s' % settings.ELASTICSEARCH_INDEX)
44 try:
45 conn.indices.create_index(settings.ELASTICSEARCH_INDEX)
47 except IndexAlreadyExistsException as ex:
48 logger.info(str(ex))
51 def search_podcasts(query):
52 """ Search for podcasts according to 'query' """
53 conn = get_connection()
55 q = {
56 "custom_score" : {
57 "query" : {
58 'query_string': {'query': query}
60 "script" : "_score * (doc.subscribers.doubleValue / 4000)"
63 results = conn.search(query=q, indices=settings.ELASTICSEARCH_INDEX,
64 doc_types='podcast',
65 model=lambda conn, doc: PodcastResult.from_doc(doc))
66 return results