utils.py 1.8 KB
Newer Older
Pablo Panero's avatar
Pablo Panero committed
1
2
3
4
5
6
7
8
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""Helper methods for CERN Search records."""

from flask import g
from flask import current_app
from invenio_search import current_search
9
from invenio_search.utils import schema_to_index, build_index_name
Pablo Panero's avatar
Pablo Panero committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26


def get_user_provides():
    """Extract the user's provides from g."""
    return [need.value for need in g.identity.provides]


def cern_search_record_to_index(record):
    """Get index/doc_type given a record.
    It tries to extract from `record['$schema']` the index and doc_type,
    the index has `CERN_SEARCH_INDEX_PREFIX` as prefix or `CERN_SEARCH_DEFAULT_INDEX_PREFIX`
    if it is not set up to be able to use the ES central service.
    If it fails, return the default values. In this case the prefix is the default value.
    :param record: The record object.
    :returns: Tuple (index, doc_type).
    """

27
    prefix = current_app.config['INDEX_PREFIX']
Pablo Panero's avatar
Pablo Panero committed
28
    index_names = current_search.mappings.keys()
29

Pablo Panero's avatar
Pablo Panero committed
30
31
32
    schema = record.get('$schema', '')
    if isinstance(schema, dict):
        schema = schema.get('$ref', '')
33
34
35
36
37
38
39
40
41
42
43

    parts = schema.split('/')

    if index_names:
        for start in range(len(parts)):
            index_name = build_index_name(*parts[start:])
            if index_name in index_names:
                if index_name.startswith(prefix) and len(index_name) > len(prefix) + 2:
                    return index_name, index_name[len(prefix) + 1:]

    current_app.logger.debug('Index {0}{1} - Doc {2}'.format(
44
        current_app.config['INDEX_PREFIX'],
45
46
47
        current_app.config['INDEXER_DEFAULT_INDEX'],
        current_app.config['INDEXER_DEFAULT_DOC_TYPE'])
    )
48
    return ('{0}{1}'.format(current_app.config['INDEX_PREFIX'],
49
50
                            current_app.config['INDEXER_DEFAULT_INDEX']),
            current_app.config['INDEXER_DEFAULT_DOC_TYPE'])