Skip to main content
 首页 » 编程设计

python之如何使用Python在ES中自动生成id

2025年05月04日22soundcode

我需要像使用 XPOST 一样存储唯一的自动 ID

因为每次启动程序,数据都会被覆盖。

但是,我找不到在 Python 中自动生成 id 的例子

有什么好的例子可以告诉我吗?

我的代码:

def saveES(output,es): 
    bodys=[] 
    i=0 
    while i<len(output)-1:  #output[len(output)-1] is space 
            json_doc=json.dumps(output[i])  
            body = { 
                    "_index":"crawler", 
                    "_type":"typed", 
                    "_id":saveES.counter, 
                    "_source":json_doc 
                    } 
            i+=1 
            bodys.append(body) 
            saveES.counter+=1 
    helpers.bulk(es,bodys) 

请您参考如下方法:

您不需要在 Python 中执行此操作——如果您索引没有 ID 的文档,Elasticsearch 将 automatically create a unique id .但是,如果由于某种原因你想在 python 中生成 id,你可以使用 uuid .