繁体   English   中英

使用 python 使用时间戳进行弹性搜索

[英]Elastic search to sort with timestamp using python

我创建了一个 python api 将接受 *.json 文件。

例如:abc.json

{
    "service_name": "httpd",
    "service_status": "DOWN",
    "host_name": "host1",
    "time": "1616600149.014236"
}

并且,使用下面的 python api 将数据推送到 ES。

@app.route('/add', methods=['POST']) def insert_data():
    #directory = '/home/user'
    dir = os.getcwd()
    os.chdir(dir)
    i = 1
    #This function will read all the json payload in the given dir and upload to ES.
    for filename in os.listdir(dir):
        if filename.endswith(".json"):
            f = open(filename)
            status_content = f.read()
            # Send the data into es
            result=(es.index(index='svc_index', ignore=400, doc_type='doc',
            id=i, body=json.loads(status_content)))
            i = i + 1
            print("result")

    return jsonify(result)

Output:

{
        "_id": "4", 
        "_index": "svc_index", 
        "_score": 1.0, 
        "_source": {
          "host_name": "host1", 
          "service_name": "httpd", 
          "service_status": "DOWN", 
          "time": "1616600143.5427265"
        }, 
        "_type": "doc"
      },

由于时间戳被存储为字符串,因此排序不起作用。 我想把最新的结果放在首位。 任何人都可以帮助解决这个问题。

谢谢!!

如果您希望 Elastic 知道 Time 属性是时间戳并将其视为时间戳,则可以将其指定为索引映射中的 Date 字段:

https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html

这应该使 Elastic 能够正确排序。

我找到了解决方案。

时间戳在 python 中使用以下查询按 desc 顺序排序。

result = es.search(index="svc_index", doc_type="doc", body={"query": {"match": {"service_name": query}},"sort":{"time": {'order': 'desc', 'mode':'max'}}}, size=1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM