gpt4 book ai didi

python - Elasticsearch DSL 中动态生成的 DocType

转载 作者:行者123 更新时间:2023-11-30 22:45:01 25 4
gpt4 key购买 nike

我正在生成一个DocType用于基于我的 ORM 构建映射和保存文档的类。

def get_doc_type(self):
attributes = {}

...
# Build attributes dictionary here

DT = type('DocType', (DocType,), attributes)
return DT

这看起来工作正常,我在映射方面没有任何问题。我的问题是当我尝试保存文档时。

这不起作用

Doc = get_doc_type()

for instance in queryset:
doc = Doc()
for field_name in fields:
attribute = getattr(instance, field_name, None)
setattr(doc, field_name, attribute)
doc.save(index)

发生这种情况时,文档确实会被保存,但是我的任何属性都不会被设置。它只是一个空文档。

我已经调试了代码以确认 field_nameattribute包含我期望的值。

这确实有效

Doc = self.get_doc_type()

for instance in queryset:
kwargs = {}

for field_name in fields:
attribute = getattr(instance, field_name, None)
kwargs.update({field_name: attribute})

doc = Doc(**kwargs)
doc.save(index=index)

当我使用此策略时,文档按预期保存,所有信息和attributes已经从我的instance传过来了进入doc .

问题

这可能是什么原因造成的?我不明白为什么这两种策略都无效。

最佳答案

我无法复制您的行为,因为一切对我来说都很好:

class DT(DocType):
pass

dt = DT()

for x in range(10):
setattr(dt, 'i_%i' % x, x)
dt.save()

DT.search().execute()[0].to_dict()

完全符合我的预期。如果它不适合您,请在 github 上提交问题,因为在这种情况下出现问题。谢谢!

顺便说一句,当我从 ORM 序列化为 elaasticsearch-dsl 时,我通常会做什么就是要有一个to_search或类似的方法直接在 Model产生 DocType实例。它使一切变得更加简单,包括使用信号同步两个数据集。

关于python - Elasticsearch DSL 中动态生成的 DocType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41316802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com