【问题标题】:Eland loading pandas dataframe to elasticsearch changes dateEland 将 pandas 数据框加载到 elasticsearch 更改日期
【发布时间】:2021-09-30 15:43:10
【问题描述】:

问候 Stackoverflowers

我一直在使用 (eland 将 pandas 数据帧作为弹性搜索文档插入。用于实现此目的的代码如下所示,并且强烈基于 url 中的代码

import eland as ed    
def save_to_elastic(data_df, elastic_engine, index_name, type_overrides_dict, chunk_size):
        """
            es_type_overrides={
                "fechaRegistro": "date",
                "fechaIncidente": "date"
            }
        """
        df = ed.pandas_to_eland(
            pd_df=data_df,
            es_client=elastic_engine,
            # Where the data will live in Elasticsearch
            es_dest_index=index_name,
            # Type overrides for certain columns, the default is keyword
            # name has been set to free text and year to a date field.
            es_type_overrides=type_overrides_dict,
            # If the index already exists replace it
            es_if_exists="replace",
            # Wait for data to be indexed before returning
            es_refresh=True,
            chunksize=chunk_size
    )

我曾经在 elasticsearch 中插入 pandas 数据框,如下所示:

from snippets.elastic_utils import save_to_elastic, conect2elastic
es = conect2elastic(user='falconiel')
save_to_elastic(data_df=siaf_consumados_elk,
                type_overrides_dict={'fechaRegistro':"date",
                                     'fechaIncidente':"date"}, 
                elastic_engine=es, 
                index_name='siaf_18032021_pc',
                chunk_size=1000)

一切正常,但是一旦我在 elasticsearch 中获得了文档,26 个日期就被错误地插入到 elasticsearch 中。 我的所有数据都从 2015 年 1 月 1 日开始。但 elasticsearch 显示 一些文档的日期为 2014 年 12 月 31 日。我一直无法找到对此的解释。为什么 pandas 数据框中的某些行具有正确的日期字段(从 2015-01-01)在加载过程中更改到去年 12 月的最后一天。对于纠正这种行为的任何帮助或见解,我将不胜感激。

我在 pandas 数据框中的日期时间列被键入为日期时间。但是,我正在尝试测试以下转换以解决该问题。他们现在还没有那么高效:

在插入调用我用来保存到弹性数据帧的函数之前,我曾尝试使用以下转换:

siaf_consumados_elk.fechaRegistro = pd.to_datetime(siaf_consumados_elk.fechaRegistro).dt.tz_localize(None)
siaf_consumados_elk.fechaRegistro = pd.to_datetime(siaf_consumados_elk.fechaRegistro, utc=True)

【问题讨论】:

  • Elasticsearch 假定它接收到的每个时间戳都采用 UTC。你在 python 的不同时区工作吗?
  • 这是一个很好的问题@MarkWalkom 我不知道UTC Python 的工作原理。事实是,我的 pandas 数据框中包含日期时间数据的列在 pandas 中被格式化为日期时间。但是,一旦将数据帧写入弹性,26 个日期从 2015-01-01 更改为 2014-12-31。

标签: python-3.x dataframe datetime elasticsearch


【解决方案1】:

事实上,问题在于 UTC。我检查了 pandas 数据框中的一些行,它们几乎减少了一天。例如,在 2021-01-02 GMT -5 注册的一条记录显示为 2021-01-01。解决方案是在调用函数之前应用相应的时区以将数据帧保存为弹性文档/索引。因此,考虑到 Mark Walkom 给出的良好观察,这是我在调用函数之前使用的:

siaf_consumados_elk.fechaRegistro = siaf_consumados_elk.fechaRegistro.dt.tz_localize(tz='America/Guayaquil')
siaf_consumados_elk.fechaIncidente = siaf_consumados_elk.fechaIncidente.dt.tz_localize(tz='America/Guayaquil')

对应时区的列表可以在以下位置找到:python time zones

这允许正确地索引时间

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 2013-10-19
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多