File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 1
1
from meilisearch .index import Index
2
2
from meilisearch .config import Config
3
3
from meilisearch ._httprequests import HttpRequests
4
+ from meilisearch .errors import MeiliSearchApiError
4
5
5
6
class Client ():
6
7
"""
@@ -80,6 +81,34 @@ def get_index(self, uid):
80
81
"""
81
82
return Index .get_index (self .config , uid = uid )
82
83
84
+ def get_or_create_index (self , uid , options = None ):
85
+ """Get an index, or create it if it doesn't exist.
86
+
87
+ Parameters
88
+ ----------
89
+ uid: str
90
+ UID of the index
91
+ options: dict, optional
92
+ Options passed during index creation (ex: primaryKey)
93
+
94
+ Returns
95
+ -------
96
+ index : Index
97
+ an instance of Index containing the information of the retrieved or newly created index
98
+ Raises
99
+ ------
100
+ HTTPError
101
+ In case of any other error found here https://docs.meilisearch.com/references/#errors-status-code
102
+ """
103
+ try :
104
+ index = Index (self .config , uid )
105
+ index .create (self .config , uid , options )
106
+ except MeiliSearchApiError as e :
107
+ if e .message != 'index already exists' :
108
+ raise e
109
+ index = self .get_index (uid )
110
+ return index
111
+
83
112
def get_all_stats (self ):
84
113
"""Get all stats of MeiliSearch
85
114
Original file line number Diff line number Diff line change @@ -56,6 +56,23 @@ def test_get_index_with_none_uid(self):
56
56
with pytest .raises (Exception ):
57
57
self .client .get_index (uid = None )
58
58
59
+ def test_get_or_create_index (self ):
60
+ """Test get_or_create_index method"""
61
+ index_1 = self .client .get_or_create_index ('book_id' )
62
+ index_2 = self .client .get_or_create_index ('book_id' )
63
+ index_3 = self .client .get_or_create_index ('book_id' )
64
+ assert index_1 .uid == index_2 .uid == index_3 .uid == 'book_id'
65
+ update = index_1 .add_documents ([{
66
+ 'id' : 1 ,
67
+ 'name' : "Some book"
68
+ }])
69
+ index_1 .wait_for_pending_update (update ['updateId' ])
70
+ documents = index_2 .get_documents ()
71
+ assert len (documents ) == 1
72
+ index_2 .delete ()
73
+ with pytest .raises (Exception ):
74
+ self .client .get_index (index_3 ).info ()
75
+
59
76
def test_index_info (self ):
60
77
"""Tests getting an index's info"""
61
78
index = self .client .get_index (uid = self .index_uid )
You can’t perform that action at this time.
0 commit comments