【问题标题】:Search a value inside a json response from elasticsearch with python使用 python 在 elasticsearch 的 json 响应中搜索一个值
【发布时间】:2019-10-24 21:11:02
【问题描述】:

我需要从 ElasticSearch 的 json 响应中获取键的值,但在下面的代码中它什么也没找到:

for hit in res['hits']['hits']:
    pattern = '"taskDefinitionId": "(.+?)"'
    result = re.findall(pattern, str(hit["_source"]))
    if result:
        print(result)

这是我正在寻找的关键:价值: "taskDefinitionId": "PEOPLE_ARE_PLAYING",

我需要在结果中获取“PEOPLE_ARE_PLAYING”

下面是整个json:

{
  "id": "tenant1#2019-06-03T19:03:50.024Z#68wer1-1rer79a-4fr5d-be9-db42cbe",
  "assignedToUser": "user",
  "attachments": [],
  "comments": [],
  "currentStatus": "COMPLETED",
  "slaExpiresAt": "2020-06-02T19:03:50.024Z",
  "history": [
    {
      "newStatus": "CLAIMED",
      "startedAt": "2019-06-03T19:03:50.024Z",
      "event": "TASK_CLAIMED"
    },
    {
      "currentStatus": "READY_TO_COMPLETE",
      "startedAt": "2019-06-03T19:09:51.072Z",
      "diff": [
        {
          "op": "add",
          "path": "/path",
          "value": {
            "address": "av dfasdfsadfhaskd",
            "name": "asd",
            "id": "1"
          }
        }
      ],
      "assignedByUser": "user",
      "event": "TASK_READY_TO_COMPLETE"
    },
    {
      "currentStatus": "COMPLETED",
      "startedAt": "2019-06-03T19:09:51.272Z",
      "assignedByUser": "asfdasdfsd",
      "event": "TASK_COMPLETED"
    }
  ],
  "assignedToGroup": "asdfsdf",
  "circuitId": "6sdf24d1-1s9sa-4f5s-b969-db4sadfc12",
  "taskDefinitionId": "PEOPLE_ARE_PLAYING",
  "finishedAt": "2019-06-03T19:09:51.272Z",
  "createdAt": "2019-06-03T19:03:50.024Z",
  "taskType": "Automatic",
  "taskDefinitionName": "Definition",
  "payload": {
    "datos": {
      "address": "sdfasdfasdfsadfsd",
      "name": "asd",
      "id": "1"
    }
  }
}

【问题讨论】:

  • 根据您的脚本,我能看到的唯一问题是hit["_source"] 是否保留您声明的 json 字符串,我尝试了正则表达式,它应该可以工作
  • 对我来说它不起作用,我不知道为什么,但我找到了更好的解决方案。我将在下面分享它。

标签: json regex python-3.x elasticsearch


【解决方案1】:

如果taskDefinitionId 是您想要的only,那么您可以使用filter_path

GET <your_index>/_search?filter_path=**.taskDefinitionId

如果你需要多个字段,你可以这样做

GET <your_index>/_search?filter_path=**.taskDefinitionId,**.currentStatus

【讨论】:

  • 感谢 Sandeep,但我需要所有数据。我正在寻找 taskDefinitionId 来决定我必须在哪里存储 json。
【解决方案2】:

终于意识到我得到了一个 dict 所以......

mydict = hit["_source"]
print(mydict["taskDefinitionId"])

【讨论】:

    猜你喜欢
    • 2020-03-10
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    相关资源
    最近更新 更多