Skip to content

Commit 224f7be

Browse files
committed
Fix inheritance of Index
Previously, inheriting `Index` from a parent class wasn't working. For example: ```python class MyBaseMetric(Metric): class Index: settings = {"number_of_shards": 2} class MyConcreteMetric(MyBaseMetric): pass ``` When indexing MyConcreteMetric, the indexes would have the default 5 shards instead of 2. This fix properly inherits the Index settings from parent classes. https://openscience.atlassian.net/browse/PLAT-1137
1 parent e3e267d commit 224f7be

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

elasticsearch_metrics/metrics.py

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from elasticsearch.exceptions import NotFoundError
66
from elasticsearch_dsl import Document, connections, Index
77
from elasticsearch_dsl.document import IndexMeta, MetaField
8+
from elasticsearch_dsl.index import DEFAULT_INDEX
89

910
from elasticsearch_metrics import signals
1011
from elasticsearch_metrics import exceptions
@@ -72,11 +73,28 @@ def __new__(mcls, name, bases, attrs): # noqa: B902
7273
# a new Index is created for every metric class
7374
@classmethod
7475
def construct_index(cls, opts, bases):
75-
i = Index(
76-
getattr(opts, "name", "*"),
77-
doc_type=getattr(opts, "doc_type", "doc"),
78-
using=getattr(opts, "using", "default"),
79-
)
76+
i = None
77+
if opts is None:
78+
# Inherit Index from base classes
79+
for b in bases:
80+
if getattr(b, "_index", DEFAULT_INDEX) is not DEFAULT_INDEX:
81+
parent_index = b._index
82+
i = Index(
83+
parent_index._name,
84+
doc_type=parent_index._mapping.doc_type,
85+
using=parent_index._using,
86+
)
87+
i._settings = parent_index._settings.copy()
88+
i._aliases = parent_index._aliases.copy()
89+
i._analysis = parent_index._analysis.copy()
90+
i._doc_types = parent_index._doc_types[:]
91+
break
92+
if i is None:
93+
i = Index(
94+
getattr(opts, "name", "*"),
95+
doc_type=getattr(opts, "doc_type", "doc"),
96+
using=getattr(opts, "using", "default"),
97+
)
8098
i.settings(**getattr(opts, "settings", {}))
8199
i.aliases(**getattr(opts, "aliases", {}))
82100
for a in getattr(opts, "analyzers", ()):

tests/test_metrics.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,9 @@ def test_inheritance(self):
138138
class MyBaseMetric(metrics.Metric):
139139
user_id = metrics.Keyword(index=True)
140140

141+
class Index:
142+
settings = {"number_of_shards": 2}
143+
141144
class Meta:
142145
abstract = True
143146

@@ -147,6 +150,7 @@ class Meta:
147150

148151
template = ConcreteMetric.get_index_template()
149152
assert template._template_name == "dummyapp_concretemetric"
153+
assert template._index.to_dict()["settings"] == {"number_of_shards": 2}
150154

151155
def test_source_may_be_enabled(self):
152156
class MyMetric(metrics.Metric):

0 commit comments

Comments
 (0)