public static function request_index(\context $context, $areaid = '',
            $priority = self::INDEX_PRIORITY_NORMAL) {
        global $DB;

        // Check through existing requests for this context or any parent context.
        list ($contextsql, $contextparams) = $DB->get_in_or_equal(
                $context->get_parent_context_ids(true));
        $existing = $DB->get_records_select('search_index_requests',
                'contextid ' . $contextsql, $contextparams, '',
                'id, searcharea, partialarea, indexpriority');
        foreach ($existing as $rec) {
            // If we haven't started processing the existing request yet, and it covers the same
            // area (or all areas) then that will be sufficient so don't add anything else.
            if ($rec->partialarea === '' && ($rec->searcharea === $areaid || $rec->searcharea === '')) {
                // If the existing request has the same (or higher) priority, no need to add anything.
                if ($rec->indexpriority >= $priority) {
                    return;
                }
                // The existing request has lower priority. If it is exactly the same, then just
                // adjust the priority of the existing request.
                if ($rec->searcharea === $areaid) {
                    $DB->set_field('search_index_requests', 'indexpriority', $priority,
                            ['id' => $rec->id]);
                    return;
                }
                // The existing request would cover this area but is a lower priority. We need to
                // add the new request even though that means we will index part of it twice.
            }
        }

        // No suitable existing request, so add a new one.
        $newrecord = [ 'contextid' => $context->id, 'searcharea' => $areaid,
                'timerequested' => (int)self::get_current_time(),
                'partialarea' => '', 'partialtime' => 0,
                'indexpriority' => $priority ];
        $DB->insert_record('search_index_requests', $newrecord);
    }