Skip to content

Commit b5058db

Browse files
Missoumiabdellatif-codoc
authored andcommitted
skip when empty objects (#83)
Co-authored-by: Abdellatif <[email protected]>
1 parent ee3dd98 commit b5058db

File tree

4 files changed

+21
-17
lines changed

4 files changed

+21
-17
lines changed

django_opensearch_dsl/documents.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ def get_indexing_queryset(
109109
"""Divide the queryset into chunks."""
110110
chunk_size = batch_size or self.django.queryset_pagination
111111
qs = self.get_queryset(filter_=filter_, exclude=exclude, count=count, alias=alias)
112-
qs = qs.order_by("pk")
112+
qs = qs.order_by("pk") if not qs.query.is_sliced else qs
113113
count = qs.count()
114114
model = self.django.model.__name__
115115
action = action.present_participle.title()
@@ -118,11 +118,15 @@ def get_indexing_queryset(
118118
if verbose:
119119
stdout.write(f"{action} {model}: 0% ({self._eta(start, done, count)})\r")
120120

121+
if count == 0:
122+
stdout.write(f"No {model} objects to {action.lower()}.\n")
123+
return
124+
121125
if batch_type == "pk_filters":
122126
pks = qs.aggregate(min=Min("pk"), max=Max("pk"))
123127
total_batches = (pks["max"] - pks["min"]) // chunk_size
124128
for batch_number, offset in enumerate(range(pks["min"], pks["max"] + 1, chunk_size), start=1):
125-
batch_qs = list(copy.deepcopy(qs.filter(pk__gte=offset, pk__lt=offset + chunk_size)))
129+
batch_qs = list(qs.filter(pk__gte=offset, pk__lt=offset + chunk_size))
126130
stdout.write(f"Processing batch {batch_number}/{total_batches}: \n")
127131
for obj in batch_qs:
128132
done += 1
@@ -132,11 +136,11 @@ def get_indexing_queryset(
132136
)
133137
yield obj
134138
if len(batch_qs) > 0:
135-
stdout.write(f"Max primary key in the current batch: {batch_qs[-1].pk}\n")
139+
stdout.write(f"Max primary key in the current {model} batch: {batch_qs[-1].pk}\n")
136140
else:
137141
total_batches = (count + chunk_size - 1) // chunk_size
138142
for batch_number, offset in enumerate(range(0, count, chunk_size), start=1):
139-
batch_qs = list(copy.deepcopy(qs[offset : offset + chunk_size].all()))
143+
batch_qs = list(qs[offset : offset + chunk_size].all())
140144
stdout.write(f"Processing batch {batch_number}/{total_batches}: \n")
141145
for obj in batch_qs:
142146
done += 1
@@ -146,7 +150,7 @@ def get_indexing_queryset(
146150
)
147151
yield obj
148152
if len(batch_qs) > 0:
149-
stdout.write(f"Max primary key in the current batch: {batch_qs[-1].pk}\n")
153+
stdout.write(f"Max primary key in the current {model} batch: {batch_qs[-1].pk}\n")
150154

151155
def init_prepare(self):
152156
"""Initialise the data model preparers once here.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
from .documen_management import manage_document
1+
from .document_management import manage_document
22
from .index_management import manage_index

django_opensearch_dsl/utils/document_management.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from typing import Any, List, Tuple
66

77
from django.core.exceptions import FieldError
8-
from django.core.management.base import OutputWrapper
8+
from django.core.management.base import CommandError, OutputWrapper
99
from django.core.management.color import color_style
1010
from django.db.models import Q
1111
from opensearchpy import OpenSearch
@@ -54,7 +54,7 @@ def manage_document(
5454
valid_models.append(model)
5555
else:
5656
stderr.write(f"Unknown object '{model}', choices are: '{registered_models}'")
57-
exit(1)
57+
raise CommandError
5858

5959
# Filter indices
6060
if indices:
@@ -63,7 +63,7 @@ def manage_document(
6363
unknown = set(indices) - set(known_name)
6464
if unknown:
6565
stderr.write(f"Unknown indices '{list(unknown)}', choices are: '{known_name}'")
66-
exit(1)
66+
raise CommandError
6767

6868
# Only keep given indices
6969
indices = list(filter(lambda i: i._name in indices, known)) # noqa
@@ -75,7 +75,7 @@ def manage_document(
7575
if not_created:
7676
stderr.write(f"The following indices are not created : {not_created}")
7777
stderr.write("Use 'python3 manage.py opensearch list' to list indices' state.")
78-
exit(1)
78+
raise CommandError
7979

8080
# Check field, preparing to display expected actions
8181
s = f"The following documents will be {action.past}:"
@@ -103,7 +103,7 @@ def manage_document(
103103
qs = model().get_queryset(filter_=filter_, exclude=exclude_, count=count, alias=database).count()
104104
except FieldError as e:
105105
stderr.write(f"Error while filtering on '{model.django.model.__name__}':\n{e}'") # noqa
106-
exit(1)
106+
raise CommandError
107107
else:
108108
s += f"\n\t- {qs} {model.django.model.__name__}."
109109
else:
@@ -121,7 +121,7 @@ def manage_document(
121121
except FieldError as e:
122122
model = index._doc_types[0].django.model.__name__ # noqa
123123
stderr.write(f"Error while filtering on '{model}' (from index '{index._name}'):\n{e}'") # noqa
124-
exit(1)
124+
raise CommandError
125125
else:
126126
s += f"\n\t- {qs} {document.django.model.__name__}."
127127

@@ -137,7 +137,7 @@ def manage_document(
137137
stdout.write("\n")
138138
break
139139
elif p.lower() in ["no", "n"]:
140-
exit(1)
140+
raise CommandError
141141

142142
result = "\n"
143143
if objects:

django_opensearch_dsl/utils/index_management.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from typing import List
33

44
import opensearchpy
5-
from django.core.management.base import OutputWrapper
5+
from django.core.management.base import CommandError, OutputWrapper
66
from django.core.management.color import color_style
77

88
from django_opensearch_dsl.enums import CommandAction
@@ -41,7 +41,7 @@ def manage_index(
4141
unknown = set(indices) - set(known_name)
4242
if unknown:
4343
stderr.write(f"Unknown indices '{list(unknown)}', choices are: '{known_name}'")
44-
exit(1)
44+
raise CommandError
4545

4646
# Only keep given indices
4747
indices = list(filter(lambda i: i._name in indices, known)) # noqa
@@ -63,7 +63,7 @@ def manage_index(
6363
stdout.write("")
6464
break
6565
elif p.lower() in ["no", "n"]:
66-
exit(1)
66+
raise CommandError
6767

6868
pp = action.present_participle.title()
6969
for index in indices:
@@ -99,7 +99,7 @@ def manage_index(
9999
stderr.write(f"{pp} index '{index._name}'...\n{error}") # noqa
100100
if not ignore_error:
101101
stderr.write("exiting...")
102-
exit(1)
102+
raise CommandError
103103
else:
104104
if verbosity:
105105
stdout.write(f"{pp} index '{index._name}'... {style.SUCCESS('OK')}") # noqa

0 commit comments

Comments
 (0)