Completed
Push — master ( a78279...04d974 )
by
unknown
10s
created

QueryBuilder.build()   B

Complexity

Conditions 4

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
c 2
b 0
f 0
dl 0
loc 27
rs 8.5806
1
class QueryBuilder:
2
    def __init__(self, query_params=None, es_version='1'):
3
        """
4
        Creates a query builder
5
6
        :param query_params: dict with query parameters
7
        """
8
        self.es_version = es_version
9
        self.query_params = query_params
10
        self.query = self._build_initial_query_string()
11
        self.filters = []
12
13
    def _build_initial_query_string(self):
14
        if self.query_params is None or 'query' not in self.query_params or self.query_params['query'] == '':
15
            return {
16
                'match_all': {}
17
            }
18
        else:
19
            all_fields = '_all' if self.es_version == '1' else '*'
20
            return {
21
                'query_string': {
22
                    'default_field': all_fields,
23
                    'query': self.query_params['query']
24
                }
25
            }
26
27
    def add_named_concept_filters(self, named_filter_concepts):
28
        """
29
        Adds named concept filters
30
31
        :param named_filter_concepts: dict with named filter concepts which will be mapped as the key as query param and the value as search string
32
        """
33
        for concept_key, concept_name in named_filter_concepts.items():
34
            self.add_concept_filter(concept_key, concept_name=concept_name)
35
36
    def add_concept_filters(self, filter_concepts):
37
        """
38
        Adds concept filters
39
40
        :param filter_concepts: list with filter concepts
41
        """
42
        for concept in filter_concepts:
43
            self.add_concept_filter(concept)
44
45
    def add_concept_filter(self, concept, concept_name=None):
46
        """
47
        Add a concept filter
48
49
        :param concept: concept which will be used as lowercase string in a search term
50
        :param concept_name: name of the place where there will be searched for
51
        """
52
        if concept in self.query_params.keys():
53
            if not concept_name:
54
                concept_name = concept
55
            if isinstance(self.query_params[concept], list):
56
                if self.es_version == '1':
57
                    es_filter = {'or': []}
58
                    for or_filter in self.query_params[concept]:
59
                        es_filter['or'].append(self._build_concept_term(concept_name, or_filter))
60
                else:
61
                    es_filter = {"bool": {"should": []}}
62
                    for or_filter in self.query_params[concept]:
63
                        es_filter["bool"]["should"].append(self._build_concept_term(concept_name, or_filter))
64
            else:
65
                es_filter = self._build_concept_term(concept_name, self.query_params[concept])
66
            self.filters.append(es_filter)
67
68
    @staticmethod
69
    def _build_concept_term(concept_name, concept):
70
        return {
71
            'term': {concept_name: str(concept).lower()}
72
        }
73
74
    def build(self):
75
        """
76
        Builds the query string, which can be used for a search query
77
78
        :return: the query string
79
        """
80
        if self.es_version == '1':
81
            if len(self.filters) > 0:
82
                return {
83
                    'filtered': {
84
                        'query': self.query,
85
                        'filter': {
86
                            'and': self.filters
87
                        }
88
                    }
89
                }
90
            else:
91
                return self.query
92
        else:
93
            query = {
94
                'bool': {
95
                    'must': self.query
96
                }
97
            }
98
            if len(self.filters) > 0:
99
                query["bool"]["filter"] = self.filters
100
            return query
101
102