Use Django's new UUIDField
[mygpo.git] / mygpo / search / index.py
blobcbcd856ebded2be2de5f6a4a2cb732666c6e7388
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)
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 "function_score" : {
57 "boost_mode": 'replace',
58 "query" : {
59 'simple_query_string': {'query': query}
61 "functions": [
63 "script_score" : {
64 'script': "_score * doc.subscribers.value"
70 results = conn.search(query=q, indices=settings.ELASTICSEARCH_INDEX,
71 doc_types='podcast',
72 model=lambda conn, doc: PodcastResult.from_doc(doc))
73 return results