utils.py 1.9 KB
Newer Older
Pablo Panero's avatar
Pablo Panero committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/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
from invenio_search.utils import schema_to_index


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).
    """
    INDEX_PREFIX = current_app.config['CERN_SEARCH_DEFAULT_INDEX_PREFIX']

    index_names = current_search.mappings.keys()
    schema = record.get('$schema', '')
    if isinstance(schema, dict):
        schema = schema.get('$ref', '')
    aux = current_app.config['CERN_SEARCH_INDEX_PREFIX']
    if aux:
        INDEX_PREFIX = aux

    index, doc_type = schema_to_index(schema, index_names=index_names)

    if index and doc_type:
39
        current_app.logger.debug('Index {0}{1} - Doc {2}'.format(INDEX_PREFIX, index, doc_type))
Pablo Panero's avatar
Pablo Panero committed
40
41
        return '{0}{1}'.format(INDEX_PREFIX, index), doc_type
    else:
42
43
44
45
46
        current_app.logger.debug('Index {0}{1} - Doc {2}'.format(
            current_app.config['CERN_SEARCH_DEFAULT_INDEX_PREFIX'],
            current_app.config['INDEXER_DEFAULT_INDEX'],
            current_app.config['INDEXER_DEFAULT_DOC_TYPE'])
        )
Pablo Panero's avatar
Pablo Panero committed
47
48
49
        return ('{0}{1}'.format(current_app.config['CERN_SEARCH_DEFAULT_INDEX_PREFIX'],
                                current_app.config['INDEXER_DEFAULT_INDEX']),
                current_app.config['INDEXER_DEFAULT_DOC_TYPE'])