{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "### Carrega pacotes necessários"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#import pip\n",
    "#pip.main(['install', 'elasticsearch'])\n",
    "# -*- coding: utf-8 -*-\n",
    "import dataiku\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "from time import time\n",
    "import os\n",
    "import sys\n",
    "from dataiku import pandasutils as pdu\n",
    "from elasticsearch import Elasticsearch, helpers\n",
    "import json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "### Conexão ao ES"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "es = Elasticsearch('http://user:pwd@server_ip:port/')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "es.info()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "### Criação de índice"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Exclui índice, se ele existir\n",
    "indice= \"datasus-sih\"\n",
    "doc_type=\"sih-type\"\n",
    "try :\n",
    "    es.indices.delete(index=indice)\n",
    "except :\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Definição de tipo para documentos\n",
    "sih_type = {\n",
    "                    \"mappings\":{\n",
    "                        'sih-type': {\n",
    "                            'properties': {\n",
    "                                  'ANO_CMPT': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'AUD_JUST': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'CAR_INT': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'CBOR': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'CEP': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'CGC_HOSP': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'CID_ASSO': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'CID_MORTE': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'CID_NOTIF': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'CNAER': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'def_cnae': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'CNES': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'CNPJ_MANT': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'INFEHOSP': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_infehosp': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'COBRANCA': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'COD_IDADE': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'COMPLEX': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'CONTRACEP1': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'CONTRACEP2': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'DIAGSEC1': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAGSEC2': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAGSEC3': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAGSEC4': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAGSEC5': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAGSEC6': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAGSEC7': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAGSEC8': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAGSEC9': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAG_PRINC': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAG_SECUN': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'DIAR_ACOM': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'DIAS_PERM': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'DT_INTER': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'DT_SAIDA': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ESPEC': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ETNIA': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'FAEC_TP': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'FINANC': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'GESTAO': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'GESTOR_COD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'GESTOR_CPF': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'GESTOR_DT': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'GESTOR_TP': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'GESTRISCO': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'HOMONIMO': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'IDADE': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'IDENT': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'IND_VDRL': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'INSC_PN': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'INSTRU': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'MARCA_UCI': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'MARCA_UTI': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'MES_CMPT': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'MORTE': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'MUNIC_MOV': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'MUNIC_RES': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'NACIONAL': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'NUM_PROC': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'NASC': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'NATUREZA': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'def_regime': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'NAT_JUR': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'NUM_FILHOS': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'N_AIH': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'PROC_REA': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'PROC_SOLIC': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'QT_DIARIAS': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'RACA_COR': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'REGCT': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'REMESSA': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'RUBRICA': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'SEQUENCIA': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'SEQ_AIH5': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'SEXO': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'SIS_JUST': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'TOT_PT_SP': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'CPF_AUT': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'TPDISEC1': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'TPDISEC2': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'TPDISEC3': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'TPDISEC4': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'TPDISEC5': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'TPDISEC6': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'TPDISEC7': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'TPDISEC8': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'TPDISEC9': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'UF_ZI': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'US_TOT': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'UTI_INT_AL': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'UTI_INT_AN': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'UTI_INT_IN': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'UTI_INT_TO': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'UTI_MES_AL': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'UTI_MES_AN': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'UTI_MES_IN': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'UTI_MES_TO': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'VAL_ACOMP': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_OBSANG': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_ORTP': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_PED1AC': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_RN': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_SADT': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_SADTSR': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_SANGUE': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_SH': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_SH_FED': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_SH_GES': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_SP': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_SP_FED': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_SP_GES': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_TOT': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_TRANSP': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_UCI': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VAL_UTI': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'VINCPREV': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ano_internacao': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ano_saida': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'cod_uf_mov': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'cod_uf_res': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'def_aglr_int': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_aglr_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_car_int': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'def_cbo': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_cir_int': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_cir_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_cobranca': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_cod_idade': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_complex': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_contracep1': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_contracep2': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_csaud_int': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_csaud_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_diag_princ_cap': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_diag_princ_cat': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_diag_princ_grupo': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_diag_princ_subcat': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_diag_secun1_cat': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_diag_secun1_grupo': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_diag_secun1_subcat': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_diarias_uti': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'def_dias_perm': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'def_esferajur': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_etnia': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_faec_tp': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_financ': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_gestao': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_gestrisco': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_homonimo': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_idade_18': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_idade_anos': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'def_idade_bas': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_idade_pub': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_ident': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_identific': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_ind_vdrl': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_instru': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_leitos': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_marca_uci': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_marca_uti': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_meso_int': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_meso_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_micro_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_morte': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_municipio_int': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_municipio_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_n_aih': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'def_nacionalidade': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_nat_jur': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_num_filhos': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_procedimento_realizado': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_procedimento_solicitado': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_raca_cor': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_reg_metr_int': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_reg_metr_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_regct': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_regiao_int': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_regiao_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_rsaud_int': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_rsaud_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_secun1_princ_cap': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_seq_aih5': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_sexo': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_tpdisec1': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_tpdisec2': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_tpdisec3': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_tpdisec4': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_tpdisec5': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_tpdisec6': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_tpdisec7': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_tpdisec8': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_tpdisec9': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_uf_int': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_uf_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_uf_sigla_int': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_uf_sigla_res': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'def_uti_mes_to': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'dia_semana_internacao': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'dia_semana_saida': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'dt_inter': {\n",
    "                                    'type': 'date'\n",
    "                                  },\n",
    "                                  'dt_saida': {\n",
    "                                    'type': 'date'\n",
    "                                  },\n",
    "                                  'idade_nascimento_anos': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ocor_ALTITUDE': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ocor_AMAZONIA': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'ocor_AREA': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'ocor_CAPITAL': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'ocor_CSAUDCOD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ocor_FRONTEIRA': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'ocor_LATITUDE': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'ocor_LONGITUDE': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'ocor_MSAUDCOD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ocor_MUNCOD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ocor_MUNNOME': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'ocor_MUNNOMEX': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'ocor_RSAUDCOD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ocor_UFCOD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ocor_codigo_adotado': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'ocor_coordenadas': {\n",
    "                                    'type': 'geo_point'\n",
    "                                  },\n",
    "                                  'ocor_uf_SIGLA_UF': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'ocorreu_uf_NOME': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'res_ALTITUDE': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'res_AMAZONIA': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'res_AREA': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'res_CAPITAL': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'res_CSAUDCOD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'res_FRONTEIRA': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'res_LATITUDE': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'res_LONGITUDE': {\n",
    "                                    'type': 'float'\n",
    "                                  },\n",
    "                                  'res_MSAUDCOD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'res_MUNCOD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'res_MUNNOME': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'res_MUNNOMEX': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'res_RSAUDCOD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'res_UFCOD': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'res_codigo_adotado': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'res_coordenadas': {\n",
    "                                    'type': 'geo_point'\n",
    "                                  },\n",
    "                                  'res_uf_CODIGO_UF': {\n",
    "                                    'type': 'long'\n",
    "                                  },\n",
    "                                  'res_uf_NOME_UF': {\n",
    "                                    'type': 'keyword'\n",
    "                                  },\n",
    "                                  'res_uf_SIGLA_UF': {\n",
    "                                    'type': 'keyword'\n",
    "                                  }\n",
    "                            }\n",
    "                        }\n",
    "                    }\n",
    "                }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#cria índice no Elasticsearch\n",
    "es.indices.create(index=indice,body=cnes_type)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "### Carrega dados preparados/transformados do Dataiku"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data_prepared = dataiku.Dataset(\"DATA_prep\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "### Recupera métricas (record_count) do dataset no Dataiku"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_metric(project_name,dataset_name,metric_ids):\n",
    "    client = dataiku.api_client()\n",
    "    current_project = client.get_project(project_name)\n",
    "    dataset = current_project.get_dataset(dataset_name)\n",
    "    metrics = dataset.compute_metrics(partition='ALL', metric_ids=metric_ids)\n",
    "    metrics = [{'metric':m[\"metricId\"],'value':int(m[\"value\"])} for m in metrics[\"result\"][\"computed\"] if m[\"metricId\"] in metric_ids][0]\n",
    "\n",
    "    return metrics"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def record_count(project_name,dataset_name):\n",
    "    return get_metric(project_name,dataset_name,['records:COUNT_RECORDS'])['value']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nrows = record_count('ETLSIH','DATA_prep')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "### Gera json para indexação"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def geraJson(df):\n",
    "    return json.loads(df.T.to_json())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Indexação em lote"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#tamanho do chunk\n",
    "chunksize = 10000\n",
    "\n",
    "#número total de chunks a serem indexados\n",
    "nchunks = nrows/chunksize\n",
    "\n",
    "#imprime o número total de documentos a serem indexados\n",
    "print(\"Documentos: %i\\n\"%nrows)\n",
    "\n",
    "res_bulk=[]\n",
    "\n",
    "for chunk,df in enumerate(data_prepared.iter_dataframes(chunksize=chunksize)):\n",
    "\n",
    "    #gera o json do chunk de dados atual (formato pronto para indexação)\n",
    "    data_json = geraJson(df)\n",
    "\n",
    "    #imprime o número do chunk atual e o total de chunks a serem indexados\n",
    "    print(\"Chunk: %i/%i\"%(chunk,nchunks))\n",
    "\n",
    "    #cria lista de ações para indexação de cada documento do chunk atual\n",
    "    lista=[]\n",
    "    for i, item in enumerate(data_json.values()):\n",
    "        data_dict = {\n",
    "            '_op_type': 'index',\n",
    "            '_index': indice,\n",
    "            '_type': doc_type,\n",
    "            '_source': item\n",
    "        }\n",
    "        lista.append(data_dict)\n",
    "\n",
    "    #indexa todos os documentos do chunk atual (bulk indexa em chunks)\n",
    "    res = helpers.bulk(client=es, actions=lista, chunk_size=1000, raise_on_error=False, raise_on_exception = False)\n",
    "    res_bulk.append(res)\n",
    "\n",
    "    print(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res_df = pd.DataFrame(res_bulk)\n",
    "res_df.columns = ['indexed_chunksize', 'errors']\n",
    "\n",
    "# Write recipe outputs\n",
    "res_Elasticsearch = dataiku.Dataset(\"bulk_elasticsearch\")\n",
    "res_Elasticsearch.write_with_schema(res_df)"
   ]
  }
 ],
 "metadata": {
  "associatedRecipe": "compute_DORJ2000-2014_from_DBC_prepared_Elasticsearch",
  "creator": "admin",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "tags": [
   "recipe-editor"
  ]
 },
 "nbformat": 4,
 "nbformat_minor": 2
}