Skip to content

Commit 21fbb80

Browse files
committed
Implement get_or_create_index method and add tests
1 parent 95156d0 commit 21fbb80

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

meilisearch/client.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from meilisearch.index import Index
22
from meilisearch.config import Config
33
from meilisearch._httprequests import HttpRequests
4+
from meilisearch.errors import MeiliSearchApiError
45

56
class Client():
67
"""
@@ -80,6 +81,34 @@ def get_index(self, uid):
8081
"""
8182
return Index.get_index(self.config, uid=uid)
8283

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+
83112
def get_all_stats(self):
84113
"""Get all stats of MeiliSearch
85114

meilisearch/tests/index/test_index.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,23 @@ def test_get_index_with_none_uid(self):
5656
with pytest.raises(Exception):
5757
self.client.get_index(uid=None)
5858

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+
5976
def test_index_info(self):
6077
"""Tests getting an index's info"""
6178
index = self.client.get_index(uid=self.index_uid)

0 commit comments

Comments
 (0)