Skip to main content
 首页 » 编程设计

python之如何使用 Python 在 ElasticSearch 中创建嵌套索引

2025年05月04日13zdz8207

我在 elasticsearch-py 中使用批量索引添加包含字典数组形式的嵌套项的文档(在本例中为 address):

{'Name': 'Smith, John', 
 'ID': '3327', 
 'Nationality': 'English', 
 'address': [ 
      { 
      'ID': '5', 
      'City': 'Milwaukee', 
      'Latlon': '43.0526,-87.9199', 
      'State': 'WI' 
      }, 
     ...  
  ] 
} 

我创建了一个操作列表,每个文档一个,如下所示:

{ 
   "_index": "myindex", 
   "_type": "mytype", 
   "_source": the_doc 
} 

然后通过helpers.bulk(es, actions)推送 Action

我想指定 address 是一个嵌套对象。我在哪里用 elasticsearch-py 向 ES 指示这个?

请您参考如下方法:

参见:https://github.com/elastic/elasticsearch-py/issues/278#issuecomment-145923743

我使用了 DSL library .我创建了一个 mytype.py 文件:

from elasticsearch_dsl import DocType, Nested, String 
 
class MyType(DocType): 
    name = String() 
    nationality = String() 
 
    address = Nested( 
        include_in_parent=True, 
        properties={ 
            'location': String(), 
            'state': String(), 
            'city': String(), 
        } 
    ) 

然后我包含这个文件并使用 include_in_parent 将映射放入 elasticsearch 中允许突出显示和其他:

from elasticsearch_dsl import Index 
from mytype import MyType 
 
myindex = Index('myindex') 
myindex.doc_type(MyType) 
myindex.create()