utils.py 2.12 KB
Newer Older
Pablo Panero's avatar
Pablo Panero committed
1
2
#!/usr/bin/python
# -*- coding: utf-8 -*-
3
4
5
6
#
# This file is part of CERN Search.
# Copyright (C) 2018-2019 CERN.
#
7
# Citadel Search is free software; you can redistribute it and/or modify it
8
# under the terms of the MIT License; see LICENSE file for more details.
Pablo Panero's avatar
Pablo Panero committed
9
10
11

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

12
from flask import current_app, g
13
14
15
from invenio_indexer.utils import default_record_to_index, schema_to_index
from invenio_search import current_search, current_search_client
from invenio_search.utils import prefix_index
Pablo Panero's avatar
Pablo Panero committed
16
17
18
19
20


def get_user_provides():
    """Extract the user's provides from g."""
    return [need.value for need in g.identity.provides]
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42


def record_from_index(record):
    """Get index/doc_type given a record.

    It tries to extract from `record['$schema']` the index and doc_type.
    If it fails, return the default values.

    :param record: The record object.
    :returns: Tuple (index, doc_type).
    """
    index_names = current_search.mappings.keys()
    schema = record.get('metadata').get('$schema', '')
    if isinstance(schema, dict):
        schema = schema.get('$ref', '')

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

    if index and doc_type:
        return index, doc_type
    else:
        return (current_app.config['INDEXER_DEFAULT_INDEX'],
Carina Antunes's avatar
Carina Antunes committed
43
                current_app.config['INDEXER_DEFAULT_DOC_TYPE'])
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67


def default_record_to_mapping(record):
    """Get mapping given a record.

    It tries to extract from `record['$schema']` the index and doc_type.
    If it fails, uses the default values.

    :param record: The record object.
    :returns: mapping
    """
    index, doc = default_record_to_index(record)
    index = prefix_index(index)
    current_app.logger.debug('Using index {idx} and doc {doc}'.format(idx=index, doc=doc))

    mapping = current_search_client.indices.get_mapping([index])
    if mapping is not None:
        doc_type = next(iter(mapping))
        current_app.logger.debug('Using mapping for {idx}'.format(idx=index))
        current_app.logger.debug('Mapping {mapping}'.format(mapping=mapping))

        return mapping[doc_type]['mappings'][doc]

    return None