Python Elasticsearch-DSL 父子关系

8

我开始使用Python库elasticsearch-dsl

我正在尝试实现一个父子关系,但是它没有起作用:

    class Location(DocType):
        name = String(analyzer='snowball', fields={'raw': String(index='not_analyzed')})
        latitude = String(analyzer='snowball')
        longitude = String(analyzer='snowball')
        created_at = Date()

   class Building(DocType):
       parent = Location()

1
代码示例?实际问题? - scooter me fecit
@ScottM 更新了代码示例。 - Renjith
在关系数据库中,实现对象关系有很多不同的选项。您可以决定嵌入文档(基本上是表中的子表),或重新实现关系数据库的“join”原语。如果您解释一下您正在考虑的方法、遇到的技术挑战等,那将会有所帮助。您的问题太广泛了,没有人能给您一个具体的答案。 - scooter me fecit
2个回答

11

elasticsearch-dsl内置了父子关系,使用MetaField实现:

class Location(DocType):
    name = String(analyzer='snowball', fields={'raw': String(index='not_analyzed')})
    latitude = String(analyzer='snowball')
    longitude = String(analyzer='snowball')
    created = Date()

    class Meta:
        doc_type = 'location' 

class Building(DocType):

    class Meta:
        doc_type = 'building'
        parent = MetaField(type='location')

如何插入和查询(感谢@Maresh):
- DSL查询: ChildDoc.get(id=child_id, routing=parent_id)
- DSL插入:我相信是 child.save(id=child_id, routing=parent_id)
- 字典插入:在字典中指定 '_parent': parent_id


1
你知道在保存子项时如何测试parent_id吗?我遇到了困难。 - Maresh
1
那么当我保存子项时,是这样做的:child.save(parent=parent.meta.id)?谢谢,很有用。请编辑您的答案,加上这个内容,因为文档中没有提到。 - Maresh
1
@Maresh 我相信应该是 child.save(id=child_id, routing=parent_id)。你能确认一下吗? - Kamil Sindi
1
确认。非常感谢。 - Maresh
1
当你说文档存储时...你的意思是将文档存储视为带有外键(基本上是“路由”)的关系型数据库? - user805981
显示剩余5条评论

1

好的,谢谢大家。对我有效的简单而凌乱的解决方案是使用:

from elasticsearch_dsl import Mapping

mcc = Mapping(typeChild)
mcc.meta('_parent', type=typeParent)
mcc.field(fieldName, 'string', fielddata=True, store=True)
mcc.save(index)

在创建父文档类型之前。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接