Skip to content

Commit 23debbd

Browse files
authored
Merge pull request #1170 from awais786/rename-index
Rename index
2 parents bdedfcf + e914130 commit 23debbd

File tree

5 files changed

+111
-5
lines changed

5 files changed

+111
-5
lines changed

docs/conf.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,9 @@
5858
# This value contains a list of modules to be mocked up.
5959
autodoc_mock_imports = ["camel_converter"]
6060

61-
html_title = 'Meilisearch Python | Documentation'
61+
html_title = "Meilisearch Python | Documentation"
6262

6363
# Add Fathom analytics script
6464
html_js_files = [
65-
("https://cdn.usefathom.com/script.js", { "data-site": "QNBPJXIV", "defer": "defer" })
65+
("https://cdn.usefathom.com/script.js", {"data-site": "QNBPJXIV", "defer": "defer"})
6666
]

meilisearch/client.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,10 @@ def swap_indexes(self, parameters: List[Mapping[str, List[str]]]) -> TaskInfo:
651651
Parameters
652652
----------
653653
indexes:
654-
List of indexes to swap (ex: [{"indexes": ["indexA", "indexB"]}).
654+
List of indexes to swap ex:
655+
1: {"indexes": ["indexA", "indexB"]} # default rename to false
656+
2: {"indexes": ["indexA", "indexB"], "rename": false}
657+
3: {"indexes": ["indexA", "indexB"], "rename": true}
655658
656659
Returns
657660
-------

meilisearch/index.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,13 +104,24 @@ def delete(self) -> TaskInfo:
104104

105105
return TaskInfo(**task)
106106

107-
def update(self, primary_key: str) -> TaskInfo:
107+
def update(self, primary_key: Optional[str] = None, new_uid: Optional[str] = None) -> TaskInfo:
108108
"""Update the index primary-key.
109109
110110
Parameters
111111
----------
112112
primary_key:
113113
The primary key to use for the index.
114+
new_uid : str, optional
115+
The new UID to rename the index.
116+
117+
Renaming behavior
118+
-----------------
119+
When ``new_uid`` is provided, this method sends a PATCH request to rename
120+
the index. After the task completes, the index exists under the new UID,
121+
but this ``Index`` instance still contains the old ``self.uid``, making it
122+
**stale**. Further operations with this instance will fail until a fresh
123+
instance is obtained. After the rename task completes, obtain a new ``Index``
124+
instance via ``client.index(new_uid)`` before making further requests.
114125
115126
Returns
116127
-------
@@ -123,7 +134,18 @@ def update(self, primary_key: str) -> TaskInfo:
123134
MeilisearchApiError
124135
An error containing details about why Meilisearch can't process your request. Meilisearch error codes are described here: https://www.meilisearch.com/docs/reference/errors/error_codes#meilisearch-errors
125136
"""
126-
payload = {"primaryKey": primary_key}
137+
if primary_key is None and new_uid is None:
138+
raise ValueError(
139+
"You must provide either 'primary_key' or 'new_uid' to update the index."
140+
)
141+
142+
payload = {}
143+
if primary_key is not None:
144+
payload["primaryKey"] = primary_key
145+
146+
if new_uid is not None:
147+
payload["uid"] = new_uid # This enables renaming
148+
127149
task = self.http.patch(f"{self.config.paths.index}/{self.uid}", payload)
128150

129151
return TaskInfo(**task)

tests/client/test_client_swap_meilisearch.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,20 @@ def test_swap_indexes_with_one_that_does_not_exist(client, empty_index):
4646
assert task.error["code"] == "index_not_found"
4747

4848

49+
def test_swap_indexes_with_one_that_does_not_exist_with_rename_as_false(client, empty_index):
50+
"""Tests swap indexes with one that does not exist."""
51+
index = empty_index("index_A")
52+
swapTask = client.swap_indexes(
53+
[
54+
{"indexes": [index.uid, "does_not_exist"], "rename": False},
55+
]
56+
)
57+
task = client.wait_for_task(swapTask.task_uid)
58+
59+
assert swapTask.type == "indexSwap"
60+
assert task.error["code"] == "index_not_found"
61+
62+
4963
def test_swap_indexes_with_itself(client, empty_index):
5064
"""Tests swap indexes with itself."""
5165
index = empty_index()
@@ -57,3 +71,21 @@ def test_swap_indexes_with_itself(client, empty_index):
5771
},
5872
]
5973
)
74+
75+
76+
def test_swap_indexes_with_one_that_does_not_exist_with_rename_as_true(client, empty_index):
77+
"""Tests swap indexes with one that does not exist."""
78+
index = empty_index("index_B")
79+
renamed_index_name = "new_index_name"
80+
swapTask = client.swap_indexes(
81+
[
82+
{"indexes": [index.uid, renamed_index_name], "rename": True},
83+
]
84+
)
85+
client.wait_for_task(swapTask.task_uid)
86+
assert swapTask.type == "indexSwap"
87+
88+
# Verify the new index UID exists
89+
renamed_index = client.index(renamed_index_name)
90+
info = renamed_index.fetch_info()
91+
assert info.uid == renamed_index_name

tests/index/test_index.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,3 +234,52 @@ def test_index_compact(client):
234234

235235
assert stats_before.number_of_documents == stats_after.number_of_documents
236236
assert stats_after.is_indexing is False
237+
238+
239+
@pytest.mark.usefixtures("indexes_sample")
240+
def test_rename_index(client):
241+
"""Test renaming an existing index."""
242+
original_uid = common.INDEX_UID
243+
new_uid = f"{original_uid}_renamed"
244+
index = client.index(original_uid)
245+
246+
# Perform the rename
247+
task_info = index.update(new_uid=new_uid)
248+
client.wait_for_task(task_info.task_uid)
249+
250+
# Verify the index now exists with the new UID
251+
renamed_index = client.index(new_uid)
252+
info = renamed_index.fetch_info()
253+
assert info.uid == new_uid
254+
255+
# # Verify the old UID no longer exists
256+
with pytest.raises(MeilisearchApiError):
257+
client.index(original_uid).fetch_info() # Assert old UID is gone
258+
259+
260+
@pytest.mark.usefixtures("indexes_sample")
261+
def test_index_update_and_rename(client):
262+
"""Test updating primary key and renaming an index together."""
263+
original_uid = common.INDEX_UID
264+
new_uid = f"{original_uid}_renamed"
265+
index = client.index(original_uid)
266+
267+
# 1. Update the primary key
268+
task_info = index.update(primary_key="objectID", new_uid=new_uid)
269+
client.wait_for_task(task_info.task_uid)
270+
271+
# Verify the index now exists with the new UID
272+
renamed_index = client.index(new_uid)
273+
info = renamed_index.fetch_info()
274+
assert info.uid == new_uid
275+
assert renamed_index.get_primary_key() == "objectID"
276+
277+
278+
@pytest.mark.usefixtures("indexes_sample")
279+
def test_index_update_without_params(client):
280+
"""Test updating primary key and renaming an index together."""
281+
index = client.index(common.INDEX_UID)
282+
with pytest.raises(ValueError) as exc:
283+
index.update()
284+
285+
assert "primary_key" in str(exc.value) or "new_uid" in str(exc.value)

0 commit comments

Comments
 (0)