【发布时间】:2018-05-31 14:34:44
【问题描述】:
我一直在尝试实施一项设计更改,但收效甚微,因为我似乎无法在任何地方找到我的问题。 目前我有一个 python 类,它创建一个数据库连接、存储索引名称(表)和其他属性(特别是它的一个 Elasticsearch 数据库连接,但这对于这个问题应该无关紧要)。
class Create:
# Functions to manipulate Index Objects
def __init__(self, index, type, host, shards=3, replicas=1):
# Create Index Object (OcrBook or OcrPage)
self.index = index
self.type = type
self.shards = shards
self.replicas = replicas
self.es_connection = Elasticsearch([{'host': host, 'port': 9200}])
与该类相关的是操作索引对象的函数,例如在数据库(集群)上创建索引(表)或以某种方式修改该表。
def create_index(self):
# Creates/Executes Index
try:
self.es_connection.indices.create(
index=self.index,
body={
'settings' : {
'number_of_shards' : self.shards,
'number_of_replicas': self.replicas,
}
})
except Exception:
CreateLog.write_log(Exception, 'Create Index Exception')
这些在同一个类中对我来说很有意义,因为与表/数据库的连接以及创建或修改该表/数据库是相互连接的。 我还有一组搜索该特定表的其他函数。我认为这些应该在一个单独的类中,而不是创建或修改表/数据库,它们只是搜索表/数据库,理想情况下可以采用由创建类初始化的任何表/数据库。目前我尝试通过执行以下操作来分解它们:
class Search(Create):
def find_book(self, bookkey):
""" Finds a Book """
try:
results = self.es_connection.search(self.index, self.type, body={
"query": {
"match": {
"BookKey": bookkey
}
}
})
return results['hits']['hits']
except Exception:
CreateLog.write_log(Exception, 'Could Not Find Book')
这适用于 Windows,但不能移植到“linux”,因为当我尝试使用搜索功能时,“类尚未初始化”。我知道这里存在设计问题,我可以将两个类合二为一来解决问题。但我想把它们分开。有没有更好的方法来“继承”(在这种情况下,我认为这不是正确的词)搜索类在“创建”类中创建的对象,有没有人有更好的方法来逻辑分离这些对象,或者是有没有更好的方法来扩展带有搜索功能的创建类?所有输入都是有帮助的!谢谢。
【问题讨论】:
标签: python-3.x class elasticsearch inheritance