使用python获取ES索引中的所有文档

2024-10-01 19:33:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将所有文档保存在一个名为:news(44908 Document)的ES索引中 然后将它们保存在数据框中

但是当运行脚本时,我只得到前十个文档

这是我的代码:

esClient = Elasticsearch()

response = esClient.search(index = 'news',
                                body = {},
                                )

#scrollId = response["_scroll_id"]
#print(scrollId)

esDocs = response["hits"]["hits"]
fields = {}
for num, doc in enumerate(esDocs):
    sourceData = doc["_source"]
    
    #response = esClient.scroll(scroll_id=scrollId, scroll = '1m')
    #scrollId = response['_scroll_id']
    #print(scrollId)
    
    for key, val in sourceData.items():
        
        if key == 'tags' or key == 'text' or key == 'title':
            
            try:
                fields[key] = np.append(fields[key], val)
            except KeyError:
                fields[key] = np.array([val])
        else:
            continue;

df = pd.DataFrame(fields)

我试着使用.scroll(),但没用。我仍然只收到10份第一批文件

我也尝试过指定size = number,但这不是我想要的

这是我的输出数据帧 Dataframe output

注:我用的是Jupyter Notbook


Tags: 数据key文档idfieldsforresponseval
2条回答

如果您试图通过pandas DataFrame API访问Elasticsearch索引,我建议使用Eland。然后,不必将所有文档加载到内存中,就可以对它们执行操作

<;披露:我是Eland的维护者,受雇于Elastic>

您需要指定size,即要返回的文档数

esClient.search(index = 'news', body = {'size': 44908})

但这太多文档了,它很可能会崩溃

相关问题 更多 >

    热门问题