courseware_index.py 21.2 KB
Newer Older
1 2
""" Code to allow module store to interface with courseware index """
from __future__ import absolute_import
3
from abc import ABCMeta, abstractmethod
4 5
from datetime import timedelta
import logging
6
import re
7
from six import add_metaclass
8 9 10

from django.conf import settings
from django.utils.translation import ugettext as _
11 12 13

from contentstore.utils import course_image_url
from course_modes.models import CourseMode
14
from eventtracking import tracker
15 16
from search.search_engine_base import SearchEngine
from xmodule.annotator_mixin import html_to_text
17
from xmodule.modulestore import ModuleStoreEnum
18
from xmodule.library_tools import normalize_key_for_search
19 20 21 22 23 24 25 26 27 28 29

# REINDEX_AGE is the default amount of time that we look back for changes
# that might have happened. If we are provided with a time at which the
# indexing is triggered, then we know it is safe to only index items
# recently changed at that time. This is the time period that represents
# how far back from the trigger point to look back in order to index
REINDEX_AGE = timedelta(0, 60)  # 60 seconds

log = logging.getLogger('edx.modulestore')


30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
def strip_html_content_to_text(html_content):
    """ Gets only the textual part for html content - useful for building text to be searched """
    # Removing HTML-encoded non-breaking space characters
    text_content = re.sub(r"(\s| |//)+", " ", html_to_text(html_content))
    # Removing HTML CDATA
    text_content = re.sub(r"<!\[CDATA\[.*\]\]>", "", text_content)
    # Removing HTML comments
    text_content = re.sub(r"<!--.*-->", "", text_content)

    return text_content


def indexing_is_enabled():
    """
    Checks to see if the indexing feature is enabled
    """
    return settings.FEATURES.get('ENABLE_COURSEWARE_INDEX', False)


49 50 51 52 53 54 55 56
class SearchIndexingError(Exception):
    """ Indicates some error(s) occured during indexing """

    def __init__(self, message, error_list):
        super(SearchIndexingError, self).__init__(message)
        self.error_list = error_list


57
@add_metaclass(ABCMeta)
E. Kolpakov committed
58
class SearchIndexerBase(object):
59
    """
60
    Base class to perform indexing for courseware or library search from different modulestores
61
    """
62
    __metaclass__ = ABCMeta
63

64 65
    INDEX_NAME = None
    DOCUMENT_TYPE = None
66
    ENABLE_INDEXING_KEY = None
67 68 69 70 71 72 73

    INDEX_EVENT = {
        'name': None,
        'category': None
    }

    @classmethod
74 75 76 77 78 79 80
    def indexing_is_enabled(cls):
        """
        Checks to see if the indexing feature is enabled
        """
        return settings.FEATURES.get(cls.ENABLE_INDEXING_KEY, False)

    @classmethod
81
    @abstractmethod
82
    def normalize_structure_key(cls, structure_key):
83 84 85
        """ Normalizes structure key for use in indexing """

    @classmethod
86
    @abstractmethod
87
    def _fetch_top_level(cls, modulestore, structure_key):
88 89 90
        """ Fetch the item from the modulestore location """

    @classmethod
91
    @abstractmethod
92
    def _get_location_info(cls, normalized_structure_key):
93 94 95
        """ Builds location info dictionary """

    @classmethod
96
    def _id_modifier(cls, usage_id):
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
        """ Modifies usage_id to submit to index """
        return usage_id

    @classmethod
    def remove_deleted_items(cls, searcher, structure_key, exclude_items):
        """
        remove any item that is present in the search index that is not present in updated list of indexed items
        as we find items we can shorten the set of items to keep
        """
        response = searcher.search(
            doc_type=cls.DOCUMENT_TYPE,
            field_dictionary=cls._get_location_info(structure_key),
            exclude_ids=exclude_items
        )
        result_ids = [result["data"]["id"] for result in response["results"]]
        for result_id in result_ids:
            searcher.remove(cls.DOCUMENT_TYPE, result_id)

115
    @classmethod
116
    def index(cls, modulestore, structure_key, triggered_at=None, reindex_age=REINDEX_AGE):
117 118 119 120
        """
        Process course for indexing

        Arguments:
121 122
        modulestore - modulestore object to use for operations

123
        structure_key (CourseKey|LibraryKey) - course or library identifier
124 125 126 127 128 129 130 131 132 133 134 135

        triggered_at (datetime) - provides time at which indexing was triggered;
            useful for index updates - only things changed recently from that date
            (within REINDEX_AGE above ^^) will have their index updated, others skip
            updating their index but are still walked through in order to identify
            which items may need to be removed from the index
            If None, then a full reindex takes place

        Returns:
        Number of items that have been added to the index
        """
        error_list = []
136
        searcher = SearchEngine.get_search_engine(cls.INDEX_NAME)
137 138 139
        if not searcher:
            return

140
        structure_key = cls.normalize_structure_key(structure_key)
141
        location_info = cls._get_location_info(structure_key)
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

        # Wrap counter in dictionary - otherwise we seem to lose scope inside the embedded function `index_item`
        indexed_count = {
            "count": 0
        }

        # indexed_items is a list of all the items that we wish to remain in the
        # index, whether or not we are planning to actually update their index.
        # This is used in order to build a query to remove those items not in this
        # list - those are ready to be destroyed
        indexed_items = set()

        def index_item(item, skip_index=False):
            """
            Add this item to the search index and indexed_items list

            Arguments:
            item - item to add to index, its children will be processed recursively

            skip_index - simply walk the children in the tree, the content change is
                older than the REINDEX_AGE window and would have been already indexed.
                This should really only be passed from the recursive child calls when
                this method has determined that it is safe to do so
            """
            is_indexable = hasattr(item, "index_dictionary")
            item_index_dictionary = item.index_dictionary() if is_indexable else None
            # if it's not indexable and it does not have children, then ignore
            if not item_index_dictionary and not item.has_children:
                return

172
            item_id = unicode(cls._id_modifier(item.scope_ids.usage_id))
173 174 175 176 177 178
            indexed_items.add(item_id)
            if item.has_children:
                # determine if it's okay to skip adding the children herein based upon how recently any may have changed
                skip_child_index = skip_index or \
                    (triggered_at is not None and (triggered_at - item.subtree_edited_on) > reindex_age)
                for child_item in item.get_children():
179 180
                    if modulestore.has_published_version(child_item):
                        index_item(child_item, skip_index=skip_child_index)
181 182 183 184 185 186 187 188 189 190 191 192 193

            if skip_index or not item_index_dictionary:
                return

            item_index = {}
            # if it has something to add to the index, then add it
            try:
                item_index.update(location_info)
                item_index.update(item_index_dictionary)
                item_index['id'] = item_id
                if item.start:
                    item_index['start_date'] = item.start

194
                searcher.index(cls.DOCUMENT_TYPE, item_index)
195 196 197 198 199 200 201 202
                indexed_count["count"] += 1
            except Exception as err:  # pylint: disable=broad-except
                # broad exception so that index operation does not fail on one item of many
                log.warning('Could not index item: %s - %r', item.location, err)
                error_list.append(_('Could not index item: {}').format(item.location))

        try:
            with modulestore.branch_setting(ModuleStoreEnum.RevisionOption.published_only):
203
                structure = cls._fetch_top_level(modulestore, structure_key)
204 205 206 207 208

                # First perform any additional indexing from the structure object
                cls.supplemental_index_information(modulestore, structure)

                # Now index the content
209
                for item in structure.get_children():
210
                    index_item(item)
211
                cls.remove_deleted_items(searcher, structure_key, indexed_items)
212 213 214 215
        except Exception as err:  # pylint: disable=broad-except
            # broad exception so that index operation does not prevent the rest of the application from working
            log.exception(
                "Indexing error encountered, courseware index may be out of date %s - %r",
216
                structure_key,
217 218 219 220 221
                err
            )
            error_list.append(_('General indexing error occurred'))

        if error_list:
louyihua committed
222
            raise SearchIndexingError('Error(s) present during indexing', error_list)
223 224 225 226

        return indexed_count["count"]

    @classmethod
227
    def _do_reindex(cls, modulestore, structure_key):
228
        """
229 230
        (Re)index all content within the given structure (course or library),
        tracking the fact that a full reindex has taken place
231
        """
232
        indexed_count = cls.index(modulestore, structure_key)
233
        if indexed_count:
234
            cls._track_index_request(cls.INDEX_EVENT['name'], cls.INDEX_EVENT['category'], indexed_count)
235 236 237
        return indexed_count

    @classmethod
238
    def _track_index_request(cls, event_name, category, indexed_count):
239 240 241 242
        """Track content index requests.

        Arguments:
            event_name (str):  Name of the event to be logged.
E. Kolpakov committed
243
            category (str): category of indexed items
244
            indexed_count (int): number of indexed items
245 246 247 248 249 250
        Returns:
            None

        """
        data = {
            "indexed_count": indexed_count,
251
            'category': category,
252 253 254 255 256 257
        }

        tracker.emit(
            event_name,
            data
        )
258

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    @classmethod
    def supplemental_index_information(cls, modulestore, structure):
        """
        Perform any supplemental indexing given that the structure object has
        already been loaded. Base implementation performs no operation.

        Arguments:
            modulestore - modulestore object used during the indexing operation
            structure - structure object loaded during the indexing job

        Returns:
            None
        """
        pass

274

E. Kolpakov committed
275
class CoursewareSearchIndexer(SearchIndexerBase):
276 277 278
    """
    Class to perform indexing for courseware search from different modulestores
    """
279 280
    INDEX_NAME = "courseware_index"
    DOCUMENT_TYPE = "courseware_content"
281
    ENABLE_INDEXING_KEY = 'ENABLE_COURSEWARE_INDEX'
282 283 284 285 286 287 288

    INDEX_EVENT = {
        'name': 'edx.course.index.reindexed',
        'category': 'courseware_index'
    }

    @classmethod
289
    def normalize_structure_key(cls, structure_key):
290 291 292 293 294
        """ Normalizes structure key for use in indexing """
        return structure_key

    @classmethod
    def _fetch_top_level(cls, modulestore, structure_key):
295 296 297 298
        """ Fetch the item from the modulestore location """
        return modulestore.get_course(structure_key, depth=None)

    @classmethod
299
    def _get_location_info(cls, normalized_structure_key):
300
        """ Builds location info dictionary """
301
        return {"course": unicode(normalized_structure_key)}
302 303 304 305 306 307 308 309

    @classmethod
    def do_course_reindex(cls, modulestore, course_key):
        """
        (Re)index all content within the given course, tracking the fact that a full reindex has taken place
        """
        return cls._do_reindex(modulestore, course_key)

310 311 312 313 314 315 316
    @classmethod
    def supplemental_index_information(cls, modulestore, structure):
        """
        Perform additional indexing from loaded structure object
        """
        CourseAboutSearchIndexer.index_about_information(modulestore, structure)

317

E. Kolpakov committed
318
class LibrarySearchIndexer(SearchIndexerBase):
319 320 321
    """
    Base class to perform indexing for library search from different modulestores
    """
322 323
    INDEX_NAME = "library_index"
    DOCUMENT_TYPE = "library_content"
324
    ENABLE_INDEXING_KEY = 'ENABLE_LIBRARY_INDEX'
325 326 327 328 329 330 331

    INDEX_EVENT = {
        'name': 'edx.library.index.reindexed',
        'category': 'library_index'
    }

    @classmethod
332
    def normalize_structure_key(cls, structure_key):
333
        """ Normalizes structure key for use in indexing """
334
        return normalize_key_for_search(structure_key)
335 336 337

    @classmethod
    def _fetch_top_level(cls, modulestore, structure_key):
338 339 340 341
        """ Fetch the item from the modulestore location """
        return modulestore.get_library(structure_key, depth=None)

    @classmethod
342
    def _get_location_info(cls, normalized_structure_key):
343
        """ Builds location info dictionary """
344
        return {"library": unicode(normalized_structure_key)}
345 346

    @classmethod
347
    def _id_modifier(cls, usage_id):
348 349 350 351 352 353 354 355
        """ Modifies usage_id to submit to index """
        return usage_id.replace(library_key=(usage_id.library_key.replace(version_guid=None, branch=None)))

    @classmethod
    def do_library_reindex(cls, modulestore, library_key):
        """
        (Re)index all content within the given library, tracking the fact that a full reindex has taken place
        """
356
        return cls._do_reindex(modulestore, library_key)
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529


class AboutInfo(object):
    """ About info structure to contain
       1) Property name to use
       2) Where to add in the index (using flags above)
       3) Where to source the properties value
    """
    # Bitwise Flags for where to index the information
    #
    # ANALYSE - states that the property text contains content that we wish to be able to find matched within
    #   e.g. "joe" should yield a result for "I'd like to drink a cup of joe"
    #
    # PROPERTY - states that the property text should be a property of the indexed document, to be returned with the
    # results: search matches will only be made on exact string matches
    #   e.g. "joe" will only match on "joe"
    #
    # We are using bitwise flags because one may want to add the property to EITHER or BOTH parts of the index
    #   e.g. university name is desired to be analysed, so that a search on "Oxford" will match
    #   property values "University of Oxford" and "Oxford Brookes University",
    #   but it is also a useful property, because within a (future) filtered search a user
    #   may have chosen to filter courses from "University of Oxford"
    #
    # see https://wiki.python.org/moin/BitwiseOperators for information about bitwise shift operator used below
    #
    ANALYSE = 1 << 0  # Add the information to the analysed content of the index
    PROPERTY = 1 << 1  # Add the information as a property of the object being indexed (not analysed)

    def __init__(self, property_name, index_flags, source_from):
        self.property_name = property_name
        self.index_flags = index_flags
        self.source_from = source_from

    def get_value(self, **kwargs):
        """ get the value for this piece of information, using the correct source """
        return self.source_from(self, **kwargs)

    def from_about_dictionary(self, **kwargs):
        """ gets the value from the kwargs provided 'about_dictionary' """
        about_dictionary = kwargs.get('about_dictionary', None)
        if not about_dictionary:
            raise ValueError("Context dictionary does not contain expected argument 'about_dictionary'")

        return about_dictionary.get(self.property_name, None)

    def from_course_property(self, **kwargs):
        """ gets the value from the kwargs provided 'course' """
        course = kwargs.get('course', None)
        if not course:
            raise ValueError("Context dictionary does not contain expected argument 'course'")

        return getattr(course, self.property_name, None)

    def from_course_mode(self, **kwargs):
        """ fetches the available course modes from the CourseMode model """
        course = kwargs.get('course', None)
        if not course:
            raise ValueError("Context dictionary does not contain expected argument 'course'")

        return [mode.slug for mode in CourseMode.modes_for_course(course.id)]

    # Source location options - either from the course or the about info
    FROM_ABOUT_INFO = from_about_dictionary
    FROM_COURSE_PROPERTY = from_course_property
    FROM_COURSE_MODE = from_course_mode


class CourseAboutSearchIndexer(object):
    """
    Class to perform indexing of about information from course object
    """
    DISCOVERY_DOCUMENT_TYPE = "course_info"
    INDEX_NAME = CoursewareSearchIndexer.INDEX_NAME

    # List of properties to add to the index - each item in the list is an instance of AboutInfo object
    ABOUT_INFORMATION_TO_INCLUDE = [
        AboutInfo("advertised_start", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
        AboutInfo("announcement", AboutInfo.PROPERTY, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("start", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
        AboutInfo("end", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
        AboutInfo("effort", AboutInfo.PROPERTY, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("display_name", AboutInfo.ANALYSE, AboutInfo.FROM_COURSE_PROPERTY),
        AboutInfo("overview", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("title", AboutInfo.ANALYSE | AboutInfo.PROPERTY, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("university", AboutInfo.ANALYSE | AboutInfo.PROPERTY, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("number", AboutInfo.ANALYSE | AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
        AboutInfo("short_description", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("description", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("key_dates", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("video", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("course_staff_short", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("course_staff_extended", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("requirements", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("syllabus", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("textbook", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("faq", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("more_info", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("ocw_links", AboutInfo.ANALYSE, AboutInfo.FROM_ABOUT_INFO),
        AboutInfo("enrollment_start", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
        AboutInfo("enrollment_end", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
        AboutInfo("org", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_PROPERTY),
        AboutInfo("modes", AboutInfo.PROPERTY, AboutInfo.FROM_COURSE_MODE),
    ]

    @classmethod
    def index_about_information(cls, modulestore, course):
        """
        Add the given course to the course discovery index

        Arguments:
        modulestore - modulestore object to use for operations

        course - course object from which to take properties, locate about information
        """
        searcher = SearchEngine.get_search_engine(cls.INDEX_NAME)
        if not searcher:
            return

        course_id = unicode(course.id)
        course_info = {
            'id': course_id,
            'course': course_id,
            'content': {},
            'image_url': course_image_url(course),
        }

        # load data for all of the 'about' modules for this course into a dictionary
        about_dictionary = {
            item.location.name: item.data
            for item in modulestore.get_items(course.id, qualifiers={"category": "about"})
        }

        about_context = {
            "course": course,
            "about_dictionary": about_dictionary,
        }

        for about_information in cls.ABOUT_INFORMATION_TO_INCLUDE:
            # Broad exception handler so that a single bad property does not scupper the collection of others
            try:
                section_content = about_information.get_value(**about_context)
            except:  # pylint: disable=bare-except
                section_content = None
                log.warning(
                    "Course discovery could not collect property %s for course %s",
                    about_information.property_name,
                    course_id,
                    exc_info=True,
                )

            if section_content:
                if about_information.index_flags & AboutInfo.ANALYSE:
                    analyse_content = section_content
                    if isinstance(section_content, basestring):
                        analyse_content = strip_html_content_to_text(section_content)
                    course_info['content'][about_information.property_name] = analyse_content
                if about_information.index_flags & AboutInfo.PROPERTY:
                    course_info[about_information.property_name] = section_content

        # Broad exception handler to protect around and report problems with indexing
        try:
            searcher.index(cls.DISCOVERY_DOCUMENT_TYPE, course_info)
        except:  # pylint: disable=bare-except
            log.exception(
                "Course discovery indexing error encountered, course discovery index may be out of date %s",
                course_id,
            )
            raise

        log.debug(
            "Successfully added %s course to the course discovery index",
            course_id
        )