【问题标题】:Choosing elasticsearch index dynamically python动态选择弹性搜索索引python
【发布时间】:2019-11-13 11:02:47
【问题描述】:

如何使用 python 动态选择索引。我目前的代码如下:

import os
import time
import datetime
from datetime import datetime
import shutil
from elasticsearch import Elasticsearch
from esindex import createIndex
client=Elasticsearch()

我有 1000 张图片,图片的名称是:1559624525_cb704087042c76bf.jpg。我将名称分为两部分,时间戳 (1559624525) 和 machid (cb704087042c76bf) 并将其写入 es 索引。

path="/home/ubuntu/images/"
for root, dirs, files in os.walk(path):
    for name in files:
        try:        
            dat=name.split('_')[0]
            machid=name.split('_')[1]
            machid=machid.split('.')[0]
            createIndex(machid)  ##this creates index dynamically
            dat=int(dat)
            dat=datetime.utcfromtimestamp(dat).strftime('%d-%m-%Y %H:%M:%S')
            dte=dat.split(' ')[0]
            id=id+1                 
            doc = {'sequence_id':id,'imagename': name, 'time_stamp': dat, 'date'=dte}
            #print(doc)
            client.index(index=machid,  body=doc)  ##this line is not working.  If i comment this out, shutil works.
            shutil.copy('/home/ubuntu/images/'+ name, '/home/ubuntu/test/')
            os.remove('/home/ubuntu/images/' + name)
        except Exception:
            continue        

如何通过动态选择索引将文档输入到 elasticsearch 中。

【问题讨论】:

  • 什么版本的 Elasticsearch?如果您运行的是早于 7.x 的 Elasticsearch 版本,您可能会缺少 client.index() 函数的 type 字段。此外,您是否看到任何错误?这里的“不工作”对您意味着什么?
  • @rusnyder 我正在使用 7.0.1,其中类型已被弃用...我根本没有收到错误。

标签: elasticsearch indexing


【解决方案1】:
  1. 在 except 块中打印异常
  2. 检查machid不为空
  3. 由于没有任何错误,请使用 Cat APIS 检查您的 ES 中创建的任何索引 curl -X GET "localhost:9200/_cat/indices"

【讨论】:

    【解决方案2】:

    显然我认为我的代码有效。在 createIndex 函数中,我有一个日期字段,该字段设置为日期,但是上面的代码将日期解析为文本。为了测试,当我在 createIndex 中将日期更改为文本时,一切都到位了。回复此内容以完成 QA 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-09
      • 2020-10-12
      • 2016-10-24
      • 1970-01-01
      相关资源
      最近更新 更多