forked from cloudant/python-cloudant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.py
More file actions
248 lines (220 loc) · 8.29 KB
/
Copy pathindex.py
File metadata and controls
248 lines (220 loc) · 8.29 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
#!/usr/bin/env python
# Copyright (c) 2015 IBM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
API module for managing/viewing query indexes.
"""
import posixpath
import json
from ._2to3 import STRTYPE, iteritems_
from ._common_util import JSON_INDEX_TYPE
from ._common_util import TEXT_INDEX_TYPE
from ._common_util import SPECIAL_INDEX_TYPE
from ._common_util import TEXT_INDEX_ARGS
from .error import CloudantArgumentError, CloudantIndexException
class Index(object):
"""
Provides an interface for managing a JSON query index. Primarily
meant to be used by the database convenience methods
:func:`~cloudant.database.CloudantDatabase.create_query_index`,
:func:`~cloudant.database.CloudantDatabase.delete_query_index`, and
:func:`~cloudant.database.CloudantDatabase.get_query_indexes`. It is
recommended that you use those methods to manage an index rather than
directly interfacing with Index objects.
:param CloudantDatabase database: A Cloudant database instance used by the
Index.
:param str design_document_id: Optional identifier of the design document.
:param str name: Optional name of the index.
:param kwargs: Options used to construct the index definition for the
purposes of index creation. For more details on valid options See
:func:`~cloudant.database.CloudantDatabase.create_query_index`.
"""
def __init__(self, database, design_document_id=None, name=None, **kwargs):
self._database = database
self._r_session = self._database.r_session
self._ddoc_id = design_document_id
self._name = name
self._type = JSON_INDEX_TYPE
self._def = kwargs
@property
def index_url(self):
"""
Constructs and returns the index URL.
:returns: Index URL
"""
return posixpath.join(self._database.database_url, '_index')
@property
def design_document_id(self):
"""
Displays the design document id.
:returns: Design document that this index belongs to
"""
return self._ddoc_id
@property
def name(self):
"""
Displays the index name.
:returns: Name for this index
"""
return self._name
@property
def type(self):
"""
Displays the index type.
:returns: Type of this index
"""
return self._type
@property
def definition(self):
"""
Displays the index definition. This could be either the definiton to
be used to construct the index or the definition as it is returned by
a GET request to the *_index* endpoint.
:returns: Index definition as a dictionary
"""
return self._def
def as_a_dict(self):
"""
Displays the index as a dictionary. This includes the design document
id, index name, index type, and index definition.
:returns: Dictionary representation of the index as a dictionary
"""
index_dict = {
'ddoc': self._ddoc_id,
'name': self._name,
'type': self._type,
'def': self._def
}
return index_dict
def create(self):
"""
Creates the current index in the remote database.
"""
payload = {'type': self._type}
if self._ddoc_id and self._ddoc_id != '':
if isinstance(self._ddoc_id, STRTYPE):
if self._ddoc_id.startswith('_design/'):
payload['ddoc'] = self._ddoc_id[8:]
else:
payload['ddoc'] = self._ddoc_id
else:
raise CloudantArgumentError(122, self._ddoc_id)
if self._name and self._name != '':
if isinstance(self._name, STRTYPE):
payload['name'] = self._name
else:
raise CloudantArgumentError(123, self._name)
self._def_check()
payload['index'] = self._def
headers = {'Content-Type': 'application/json'}
resp = self._r_session.post(
self.index_url,
data=json.dumps(payload, cls=self._database.client.encoder),
headers=headers
)
resp.raise_for_status()
self._ddoc_id = resp.json()['id']
self._name = resp.json()['name']
return
def _def_check(self):
"""
Checks that the only definition provided is a "fields" definition.
"""
if list(self._def.keys()) != ['fields']:
raise CloudantArgumentError(124, self._def)
def delete(self):
"""
Removes the current index from the remote database.
"""
if not self._ddoc_id:
raise CloudantArgumentError(125)
if not self._name:
raise CloudantArgumentError(126)
ddoc_id = self._ddoc_id
if ddoc_id.startswith('_design/'):
ddoc_id = ddoc_id[8:]
url = posixpath.join(self.index_url, ddoc_id, self._type, self._name)
resp = self._r_session.delete(url)
resp.raise_for_status()
return
class TextIndex(Index):
"""
Provides an interface for managing a text query index. Primarily
meant to be used by the database convenience methods
:func:`~cloudant.database.CloudantDatabase.create_query_index`,
:func:`~cloudant.database.CloudantDatabase.delete_query_index`, and
:func:`~cloudant.database.CloudantDatabase.get_query_indexes`. It is
recommended that you use those methods to manage an index rather than
directly interfacing with TextIndex objects.
:param CloudantDatabase database: A Cloudant database instance used by the
TextIndex.
:param str design_document_id: Optional identifier of the design document.
:param str name: Optional name of the index.
:param kwargs: Options used to construct the index definition for the
purposes of index creation. For more details on valid options See
:func:`~cloudant.database.CloudantDatabase.create_query_index`.
"""
def __init__(self, database, design_document_id=None, name=None, **kwargs):
super(TextIndex, self).__init__(
database,
design_document_id,
name,
**kwargs
)
self._type = TEXT_INDEX_TYPE
def _def_check(self):
"""
Checks that the definition provided contains only valid arguments for a
text index.
"""
if self._def != dict():
for key, val in iteritems_(self._def):
if key not in list(TEXT_INDEX_ARGS.keys()):
raise CloudantArgumentError(127, key)
if not isinstance(val, TEXT_INDEX_ARGS[key]):
raise CloudantArgumentError(128, key, TEXT_INDEX_ARGS[key])
class SpecialIndex(Index):
"""
Provides an interface for viewing the "special" primary index of a database.
Primarily meant to be used by the database convenience method
:func:`~cloudant.database.CloudantDatabase.get_query_indexes`. It is
recommended that you use that method to view the "special" index rather than
directly interfacing with the SpecialIndex object.
"""
def __init__(
self,
database,
design_document_id=None,
name='_all_docs',
**kwargs
):
super(SpecialIndex, self).__init__(
database,
design_document_id,
name,
**kwargs
)
self._type = SPECIAL_INDEX_TYPE
def create(self):
"""
A "special" index cannot be created. This method is disabled for a
SpecialIndex object.
"""
raise CloudantIndexException(101)
def delete(self):
"""
A "special" index cannot be deleted. This method is disabled for a
SpecialIndex object.
"""
raise CloudantIndexException(102)