简体   繁体   English

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

[英]Elastic search to sort with timestamp using python

I have created a python api which will accept the *.json file.我创建了一个 python api 将接受 *.json 文件。

for ex: abc.json例如:abc.json

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

and, push the data to the ES using below python api.并且,使用下面的 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: Output:

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

Since timestamp is being stored as string, sorting is not working.由于时间戳被存储为字符串,因此排序不起作用。 I wanted to bring the latest result on top.我想把最新的结果放在首位。 Could anyone please help into this.任何人都可以帮助解决这个问题。

Thanks!!谢谢!!

If you want Elastic to know that the Time property is a timestamp and treat it as such, you can specify it as a Date field in the index mapping:如果您希望 Elastic 知道 Time 属性是时间戳并将其视为时间戳,则可以将其指定为索引映射中的 Date 字段:

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

That should enable Elastic to sort it correctly.这应该使 Elastic 能够正确排序。

I have found the solution.我找到了解决方案。

timestamp is getting sorted in desc order with the following query in python.时间戳在 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